Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Schwartzian Transform vs. Building Hash of Function Results, Then Sorting on Function Results

by davebaker (Pilgrim)
on Oct 16, 2006 at 18:54 UTC ( [id://578571]=note: print w/replies, xml ) Need Help??


in reply to Schwartzian Transform

I'm trying to better understand the Schwartzian Tranform (sorting a list by computable field). I've read the explanation in the Perl Cookbook, 2d ed. recipe 4.16. I also enjoyed Randal's 1996 article in the Unix Review, which describes a sortable-hash technique before it goes on to show the map-sort-map transform technique. The sortable-hash technique intrigues me. Other than coolness and nicer-looking code, what is the advantage of this:
my @output = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, expensive_func($_)] } @input;
over this:
foreach $_ (@input) { $result_for{$_} = expensive_func($_); } my @output = sort { $result_for{$a} cmp $result_for{$b} } @input;

Replies are listed 'Best First'.
Re: Schwartzian Transform vs. Building Hash of Function Results, Then Sorting on Function Results
by merlyn (Sage) on Oct 16, 2006 at 19:27 UTC
    Consider sorting a list of objects that have a stringification overload and two of those objects stringify to the same string. With the ST, everything just works. With the hash method, the two objects collapse to the same hash entry.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

Re: Schwartzian Transform vs. Building Hash of Function Results, Then Sorting on Function Results
by Limbic~Region (Chancellor) on Oct 16, 2006 at 19:10 UTC
    davebaker,
    In both cases, you are calculating the expensive_func() only once per item and sorting the list based off the result of the expensive_func(). The biggest difference is that in the standard ST, you do it in a single step and have no left over variable.

    Cheers - L~R

      Thanks! I hadn't considered the left over variable. I'd want to add this line before my sorted-hash code snippet:
      my %result_for;
      (That doesn't eliminate any drawbacks to having a left over variable as compared to the ST, but it would be safer coding I think.)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-03-19 03:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found