Schwartzian Transform - Example

Example

For example, to sort a list of files by their modification times, a naive approach might be as follows:

function naiveCompare(file a, file b) { return modificationTime(a) < modificationTime(b) } // Assume that sort(list, comparisonPredicate) sorts the given list using // the comparisonPredicate to compare two elements. sortedArray := sort(filesArray, naiveCompare)

Unless the modification times are memoized for each file, this method requires their re-computing every time a file is compared in the sort. Using the Schwartzian transform, the modification time is calculated only once per file.

A Schwartzian transform involves the functional idiom described above, which does not use temporary arrays.

The same algorithm can be written procedurally to better illustrate how it works, but this requires using temporary arrays, and is not a Schwartzian transform. The following example pseudo-code implements the algorithm in this way:

for each file in filesArray insert array(file, modificationTime(file)) at end of transformedArray function simpleCompare(array a, array b) { return a < b } transformedArray := sort(transformedArray, simpleCompare) for each file in transformedArray insert file at end of sortedArray

Read more about this topic:  Schwartzian Transform

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)