typestar

Ord and sorting in Haskell

Three orderings of one list: sortBy with a comparator, sortOn with a key, and Down to reverse.

module RaceResults where

import Data.List (sortBy, sortOn)
import Data.Ord (Down (..), comparing)

-- Each runner with the seconds they posted.
results :: [(String, Double)]
results = [("ana", 12.4), ("bo", 11.9), ("cy", 13.1), ("di", 11.9)]

-- comparing lifts an accessor into the comparison sortBy wants.
byTime :: [(String, Double)]
byTime = sortBy (comparing snd) results

-- sortOn computes each key once instead of on every comparison.
byName :: [(String, Double)]
byName = sortOn fst results

-- Down reverses any Ord instance, which is how you sort descending.
slowestFirst :: [(String, Double)]
slowestFirst = sortOn (Down . snd) results

How it works

  1. byTime calls sortBy (comparing snd), since comparing turns an accessor into the comparison sortBy expects.
  2. byName uses sortOn fst, which computes each key once instead of on every comparison.
  3. slowestFirst wraps that key as sortOn (Down . snd), and Down reverses any Ord instance.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
648
Tokens
117
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 3 of 3 in Typeclasses, step 21 of 27 in Language basics.

← Previous Next →