Haskell Sorting
Sorting puts the items of a list into a chosen order. The sort and sortOn helpers in Data.List do this work.
sort orders numbers
The import brings sort in for this block. The numbers come out in rising order.
import Data.List (sort)
main :: IO ()
main = print (sort [5, 2, 8, 1])sort orders words
Words sort in alphabetical order. The import line brings sort in again for this block.
import Data.List (sort)
main :: IO ()
main = print (sort ["pear", "apple", "kiwi"])sortOn sorts pairs by one part
The first print sorts the pairs by their first item. The second print sorts its pairs by their second item.
import Data.List (sortOn)
main :: IO ()
main = do
print (sortOn fst [(2, "b"), (1, "a")])
print (sortOn snd [("a", 3), ("b", 1)])Example
import Data.List (sortOn)
main :: IO ()
main = print (sortOn fst [(1, "first"), (2, "third"), (1, "second")])Key points
- sort: a Data.List helper that puts a list into rising order.
- Text order: sort puts words in alphabetical order.
- sortOn: a Data.List helper that sorts by a value worked out from each item.
- sortOn fst: a sort of pairs by their first item.
- sortOn snd: a sort of pairs by their second item.
- Stable sort: items with equal keys keep the order they had in the first list.
In this example, sortOn fst orders the pairs by their first number. The two pairs with key 1 keep their first list order, with first before second. That kept order shows the sort is stable.
Note
sorting builds a new list, and the first list stays as it was.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does sortOn snd [("a", 2), ("b", 1)] give?