Some other languages provide a convenient interface to the same optimization as the Schwartzian transform: • In
Python 2.4 and above, both the function and the in-place method take a parameter that allows the user to provide a "key function" (like in the examples above). In Python 3 and above, use of the key function is the only way to specify a custom sort order (the previously supported parameter that allowed the user to provide a "comparison function" was removed). Before Python 2.4, developers would use the lisp-originated decorate–sort–undecorate (DSU) idiom, usually by wrapping the objects in a (sortkey, object)
tuple. • In
Ruby 1.8.6 and above, the abstract class (which includes s) contains a method, which allows specifying the "key function" (like in the examples above) as a code block. • In
D 2 and above, the function is available. It might require less temporary data and be faster than the Perl idiom or the decorate–sort–undecorate idiom present in Python and Lisp. This is because sorting is done in-place, and only minimal extra data (one array of transformed elements) is created. •
Racket's core sort function accepts a #:key keyword argument with a function that extracts a key, and an additional #:cache-keys? requests that the resulting values are cached during sorting. For example, a convenient way to shuffle a list is . • In
PHP 5.3 and above the transform can be implemented by use of , e.g. to work around the limitations of the unstable sort algorithms in PHP. function spaceballs_sort(array& $a): void { array_walk($a, function(&$v, $k) { $v = array($v, $k); }); asort($a); array_walk($a, function(&$v, $_) { $v = $v[0]; }); } • In
Elixir, the and methods allow users to perform a Schwartzian transform for any module that implements the protocol. • In
Raku, one needs to supply a comparator lambda that only takes 1 argument to perform a Schwartzian transform under the hood: @a.sort( { $^a.Str } ) # or shorter: @a.sort(*.Str) would sort on the string representation using a Schwartzian transform, @a.sort( { $^a.Str cmp $^b.Str } ) would do the same converting the elements to compare just before each comparison. • In
Rust, somewhat confusingly, the method does
not perform a Schwartzian transform as it will not allocate additional storage for the key, it will call the key function for each value for each comparison. The method will compute the keys once per element. • In
Haskell, the sortOn function from the base library performs a Schwartzian transform. ==References==