ArticleslgStudy

computer science

Schwartzian transform

Schwartzian transform is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Schwartzian transform rather than just read about it. In short: In computer programming, the Schwartzian transform is a technique used to improve the efficiency of sorting a list of items. This idiom is appropriate for comparison-based sorting when the ordering is actually based on the ordering of a certain property (the key) of the elements, where computing that property is an expensive operation that should be performed a minimal number of times.

Key takeaways

  • Schwartzian transform belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Schwartzian transform to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Schwartzian transform from memory before moving on to harder problems.

Reference excerpt

In computer programming, the Schwartzian transform is a technique used to improve the efficiency of sorting a list of items. This idiom is appropriate for comparison-based sorting when the ordering is actually based on the ordering of a certain property (the key) of the elements, where computing that property is an expensive operation that should be performed a minimal number of times. The Schwartzian transform is notable in that it does not use named temporary arrays. The Schwartzian transform is a version of a Lisp idiom known as decorate-sort-undecorate, which avoids recomputing the sort keys by temporarily associating them with the input items. This approach is similar to memoization, which avoids repeating the calculation of the key corresponding to a specific input value. By comparison, this idiom assures that each input item's key is calculated exactly once, which may still result in repeating some calculations if the input data contains duplicate items. The idiom is named after Randal L. Schwartz, who first demonstrated it in Perl shortly after the release of Perl 5 in 1994. The term "Schwartzian transform" applied solely to Perl programming for a number of years, but it has later been adopted by some users of other languages, such as Python, to refer to similar idioms in those languages. However, the algorithm was already in use in other languages (under no specific name) before it was popularized among the Perl community in the form of that particular idiom by Schwartz. The term "Schwartzian transform" indicates a specific idiom, and not the algorithm in general. For example, to sort the word list ("aaaa","a","aa") according to word length: first build the list (["aaaa",4],["a",1],["aa",2]), then sort it according to the numeric values getting (["a",1],["aa",2],["aaaa",4]), then strip off the numbers and you get ("a","aa","aaaa"). That was the algorithm in general, so it does not count as a transform. To make it a true Schwartzian transform, it would be done in Perl like this:

The Perl idiom The general form of the Schwartzian transform is:

Here 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 [item, value]); then the list of lists produced by map is fed into sort, which sorts it according to the values previously calculated (list of [item, value] ⇒ sorted list of [item, value]); 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 [item, value] ⇒ 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.

Efficiency analysis Without the Schwartzian transform, the sorting in the example above would be written in Perl like this:

While it is shorter to code, the naive approach here could be much less efficient if the key function (called foo in the example above) is expensive to compute. This is because the code inside the brackets is evaluated each time two elements need to be compared. An optimal comparison sort performs O(n log n) comparisons (where n is the length of the list), with 2 calls to foo every comparison, resulting in O(n log n) calls to foo. In comparison, using the Schwartzian transform, we only make 1 call to foo per element, at the beginning map stage, for a total of n calls to foo. However, if the function foo is relatively simple, then the extra overhead of the Schwartzian transform may be unwarranted.

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 re-computing them 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[2] < b[2] }

transformedArray := sort(transformedArray, simpleCompare)

for each file in transformedArray insert file[1] at end of sortedArray

History The first known online appearance of the Schwartzian transform is a December 16, 1994 posting by Randal Schwartz to a thread in comp.unix.shell Usenet newsgroup, crossposted to comp.lang.perl. (The current version of the Perl Timeline is incorrect and refers to a later date in 1995.) The thread began with a question about how to sort a list of lines by their "last" word:

adjn:Joshua Ng adktk:KaLap Timothy Kwong admg:Mahalingam Gobieramanan admln:Martha L. Nangalama

Schwartz responded with:

This code produces the result:

admg:Mahalingam Gobieramanan adktk:KaLap Timothy Kwong admln:Martha L. Nangalama adjn:Joshua Ng

Schwartz noted in the post that he was "Speak[ing] with a lisp in Perl", a reference to the idiom's Lisp origins. The term "Schwartzian transform" itself was coined by Tom Christiansen in a follow-up reply. Later posts by Christiansen made it clear that he had not intended to name the construct, but merely to refer to it from the original post: his attempt to finally name it "The Black Transform" did not take hold ("Black" here being a pun on "schwar[t]z", which means black in German).

Comparison to other languages Some other languages provide a convenient interface to the same optimization as the Schwartzian transform:

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Schwartzian transform

Start with the simplest possible case. Write down what Schwartzian transform claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Schwartzian transform before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Schwartzian transform ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Schwartzian transform

In research
Schwartzian transform appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Schwartzian transform in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Schwartzian transform is common in secondary-school and first-year university syllabi. It links to neighbouring topics Perl, Sorting algorithms, so understanding it makes those chapters shorter.
In everyday life
Look for Schwartzian transform outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Schwartzian transform” →

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Schwartzian transform in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Schwartzian transform means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Schwartzian transform out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Schwartzian transform in simple terms?

In computer programming, the Schwartzian transform is a technique used to improve the efficiency of sorting a list of items. This idiom is appropriate for comparison-based sorting when the ordering is actually based on the ordering of a certain property (the key) of the elements, where computing th…

Why does Schwartzian transform matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Schwartzian transform?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Schwartzian transform.

Tags

  • Perl
  • Sorting algorithms

Keep exploring