On IRC today someone asked for a function that computes the mode of a list. This is the same as finding the most common element in a list. One simple solution is a nice display of composition of smaller abstraction functions:
mostCommon :: Ord a => [a] -> a
mostCommon = head . maximumBy (comparing length) . group . sort
And a single example:
; mostCommon "Haskell"
To read the function mostCommon, it is best to read from right to help:
- sort: put the elements in order, i.e. "Haeklls".
- group: group consecutive elemnts, i.e. ["H","a","e","k","ll","s"]. It would be entirely reasonable to have a groupSet function that did grouping of non-consecutive elements, and I often use such a function.
- maximumBy (comparing length): find the maximum value, looking only at the number of elements in each list, i.e. "ll".
- head: take a representative value from the list, i.e. 'l'.
It is easy to see that by combining functions that have already been written, tested and documented, it is possible to come up with very succinct operations.