Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Schwartzian Transform

by chromatic (Archbishop)
on Dec 25, 1999 at 09:21 UTC ( #1394=perlcraft: print w/ replies, xml ) Need Help??

   1: #Want to sort a complex data structure by some element
   2: #efficiently?  For example, how do you sort an array
   3: #of strings by their length?  Use the transform:
   4:    @sorted = map { $_->[1] }
   5:    sort { $a->[0] <=> $b->[0] }
   6:    map { [ length $_, $_ ] } @strings;
   7: 
   8: #Confused?  Put in temporary arrays, 
   9: #just to see what we're doing.
  10: 
  11: # create a temporary array of anonymous arrays
  12: # (0: length of the string, 1: the string)
  13:    @temp = map { [ length $_, $_ ] } @strings;
  14: # sort by length
  15:    @temp = sort { $a->[0] <=> $b->[0] };
  16: # grab just the strings and put them in @ordered
  17:    @sorted = map { $_->[1] } @temp;
  18: 
  19: #Knowing the context of certain operations
  20: # and being able to chain them together
  21: # is crucial to a deep and idiomatic
  22: # understanding of Perl.

Comment on Schwartzian Transform
Download Code
Re: Schwartzian Transform
by I0 (Priest) on Jan 02, 2001 at 18:06 UTC
    You probably meant @temp = sort { $a->[0] <=> $b->[0] } @temp;

    Although, given a @temp array, it benchmarks faster to do
    @temp = map { length $_ } @strings; @sorted = @strings[sort{$temp[$a]<=>$temp[$b]} $[..$#temp];

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlcraft [id://1394]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2014-10-02 05:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (49 votes), past polls