Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: how does these map statements work

by AppleFritter (Vicar)
on Aug 06, 2014 at 09:40 UTC ( [id://1096409]=note: print w/replies, xml ) Need Help??


in reply to how does these map statements work

This is a standard technique called the Schwartzian Transform (after Randal L. Schwartz, aka merlyn, though he wasn't the one who named it). The idea is that you augment your data with additional information (that's the innermost map), then use that extra info to sort (the sort call, naturally), and finally discard it again (the outermost map), leaving only the original data, in the right order.

The reason why this is done is that often, you want to sort based on the result of some potentially expensive operation. Using the Schwartzian transform, you only have to perform this operation once per item, rather than twice per call to your comparison function. Since Perl's sort (mergesort, if you're curious) is O(n log(n)), and this is optimal for sorting algorithms in the general case, the Schwartzian transform is almost always a good idea if you need to process list elements in some fashion before sorting -- and the performance gain will be larger the more expensive processing an item is.

Here's merlyn's classic column on the technique.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-26 00:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found