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
byTimecallssortBy (comparing snd), sincecomparingturns an accessor into the comparison sortBy expects.byNameusessortOn fst, which computes each key once instead of on every comparison.slowestFirstwraps that key assortOn (Down . snd), andDownreverses any Ord instance.
Keywords and builtins used here
DoubleDownStringbyNamebyTimecomparingimportmoduleresultsslowestFirstsortBysortOnwhere
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.
Step 3 of 3 in Typeclasses, step 21 of 27 in Language basics.