Schwartzian Transform - The Perl Idiom

The Perl Idiom

The general form of the Schwartzian Transform is:

@sorted = map { $_-> } sort { $a-> cmp $b-> } map { } @unsorted;

Where foo($_) represents an expression that takes $_ (each item of the list in turn) and produces the corresponding value that is to be compared in its stead.

Reading from right to left (or from the bottom to the top):

  • the original list @unsorted is fed into a map operation that wraps each item into a (reference to an anonymous 2-element) array consisting of itself and the calculated value that will determine its sort order (list of item becomes a list of );
  • then the list of lists produced by map is fed into sort, which sorts it according to the values previously calculated (list of ⇒ sorted list of );
  • finally, another map operation unwraps the values (from the anonymous array) used for the sorting, producing the items of the original list in the sorted order (sorted list of ⇒ sorted list of item).

The use of anonymous arrays ensures that memory will be reclaimed by the Perl garbage collector immediately after the sorting is done.

Read more about this topic:  Schwartzian Transform

Famous quotes containing the word idiom:

    The “sayings” of a community, its proverbs, are its characteristic comment upon life; they imply its history, suggest its attitude toward the world and its way of accepting life. Such an idiom makes the finest language any writer can have; and he can never get it with a notebook. He himself must be able to think and feel in that speech—it is a gift from heart to heart.
    Willa Cather (1873–1947)