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

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

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;
• Comment on Schwartzian Transform vs. Building Hash of Function Results, Then Sorting on Function Results

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.)

Create A New User
Node Status?
node history
Node Type: note [id://578571]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
As of 2018-02-26 03:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
When it is dark outside I am happiest to see ...

Results (316 votes). Check out past polls.

Notices?