Keeping the Comb Strokes in Order
A sheet of paste paper can change character with a single pass of a comb. Drag it straight through the wet colour and you get stripes; wobble your wrist and those stripes become waves. After a session at the table, I have a row of swatches I want to arrange by colour intensity while keeping the patterns in the order I made them.
That last detail calls for a stable sort. When two items have the same sort key, a stable sort preserves their original relative order. Here the numbers are deliberately simple intensity categories, not measurements of pigment or a recipe for mixing paint.
fn main() {
let mut swatches = [(2, "stripes"), (1, "dots"), (2, "waves"), (1, "crosshatch")];
swatches.sort_by_key(|swatch| swatch.0);
for (intensity, pattern) in swatches {
println!("{intensity}: {pattern}");
}
}
The output puts dots before crosshatch and stripes before waves, just as they appeared on the table:
1: dots
1: crosshatch
2: stripes
2: waves
Haskell’s sortOn makes the same promise, using the first member of each pair as the key:
import Data.List (sortOn)
main :: IO ()
main = do
let swatches = [(2, "stripes"), (1, "dots"), (2, "waves"), (1, "crosshatch")]
mapM_ print (sortOn fst swatches)
That version prints tuples, but their order is the same. Stability is useful whenever the existing sequence carries meaning: a previous arrangement, a timestamp, or the order in which a maker laid down marks. It also has a cost worth considering. Rust’s stable slice sort may allocate auxiliary storage; if the order of equal keys does not matter, its unstable sort offers a different trade-off. For my swatches, preserving the sequence is part of the composition.