RockPaperScissors

LizardSpock

Schwartzian Transform

| Comments

I recently heard about the Schwartzian transform, which is a sorting idiom from perl. It allows an array of objects to be efficiently sorted by any property. Part of the cleverness is the use of anonymous arrays which allows them to be garbage collected quickly.

Wikipedia has a detailed description, however the general form (in perl) is:

@sorted = map  { $_->[0] }
          sort { $a->[1] cmp $b->[1] }
          map  { [$_, foo($_)] }
              @unsorted;

A good history of it can be read here.

My point of bring all of this up other than pointing out a cool sorting algorithm is that any ruby class including Enumerable (Arrays, Hashes etc) has this built in with the .sort_by method.

Comments