Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re^2: Rosetta Code: Long List is Long (Updated Solutions)

by Tux (Canon)
on Dec 05, 2022 at 15:33 UTC ( [id://11148568]=note: print w/replies, xml ) Need Help??


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?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11148568]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (2)
As of 2024-04-24 04:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found