While using maximumBy
with comparing length
or compare `on` length
will do the job just fine for short lists, note that this is not a very efficient solution if the lists are long, since each time the algorithm compares two lists, it will re-calculate their lengths.
For example, if we have a very long first list, followed by many short lists, using maximumBy
will be very slow since the length of the first list will be re-calculated at each step.
> import Data.List
> import Data.Ord
> let xs = replicate 50000 'a' : replicate 50000 "b"
> maximumBy (comparing length) xs
<snip>
(16.09 secs, 98338680 bytes)
We can get a more efficient solution by caching the lengths of the lists:
> let longest xss = snd $ maximumBy (comparing fst) [(length xs, xs) | xs <- xss]
> longest xs
<snip>
(0.35 secs, 91547296 bytes)
Of course, this might not make a big difference if your lists are small, but it's worth taking note of.