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"
'l'
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'.
If asked to write the same function in Javascript (say), I would have started with a Hash table that looped counting the number of occurrences of each letter, then done a loop through this to find the maximum. The code would have been longer, and more prone to bugs.
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.


