

mostCommon :: Ord a => [a] -> a

mostCommon = head . maximumBy (comparing length) . group . sort





; mostCommon "Haskell"

'l'



mostCommon



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' .



Haskell has great support for abstraction: small functions can be written which do one general thing. Haskell also has great support for composition: putting small functions together is easy.On IRC today someone asked for a function that computes theof 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:And a single example:To read the function, it is best to read from right to help: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.