in reply to Re: Rosetta Code: Long List is Long (Updated Solutions)
in thread Rosetta Code: Long List is Long

Some wiser monk might correct me, but I think this difference is because "simple" blocks can be internally optimized

(edited: typoes corrected after reading the replies)

my @sorted = sort @unsorted; my @sorted = sort { $a <=> $b } @unsorted; my @sorted = sort { $a cmp $b } @unsorted;

Are all internally optimized to something simple and efficient. Once the block gets more complicated, like having multiple statements and/or multiple expressions, every block has to be wrapped in scopes *for each call* to that sub. This is one of the reasons why the Larry-Rossler Guttman-Rosler Transform is so efficient.

my @sorted = sort { $a->{id} <=> $b->{id} || $a->{foo} cmp $b->{foo} } + @unsorted; # SLOW my @sorted = map { $_->[1] } sort { $a->[0] cmp $b->[0] } map { pack " +l>A*", $_->{id}, $_->{foo} } @unsorted; # FAST

Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^3: Rosetta Code: Long List is Long (Updated Solutions)
by jwkrahn (Abbot) on Dec 09, 2022 at 20:53 UTC
    This is one of the reasons why the Larry-Rossler is so efficient.

    I think that you are thinking of the Guttman-Rosler Transform?

    my @sorted = sort { $b->{id} <=> $b->{id} || $a->{foo} cmp $b->{foo} } + @unsorted; # SLOW

    Comparing $b->{id} to itself will not work very well.

      I think that you are thinking of the Guttman-Rosler Transform?

      Agreed. BTW I believe the GRT is generally faster than the Schwartzian Transform (this node has more detail on sorting history in Perl).

      Though fond of the GRT, I couldn't make it work for this problem because of the unusual requirement to sort descending by count yet ascending by name (it would work nicely to sort both fields ascending via the classic pack "NA*" trick). If anyone can see a way to make GRT work for this problem, please let us know.

        Perhaps add a negative sign to the numbers before sorting and remove it after?