Scala has a function groupBy
on lists that accepts a function for extracting keys from list items, and returns another list where the items are tuples consisting of
Putting a trace
in f
reveals that, with @Niklas solution, f
is evaluated 3 times for each element on any list of length 2 or more. I took the liberty of modifying it so that f
is applied to each element only once. It's not clear however whether the cost of creating and destroying tuples is less than the cost of evaluating f
multiple times (since f
can be arbitrary).
import Control.Arrow ((&&&))
import Data.List
import Data.Function
myGroupBy' :: (Ord b) => (a -> b) -> [a] -> [(b, [a])]
myGroupBy' f = map (fst . head &&& map snd)
. groupBy ((==) `on` fst)
. sortBy (compare `on` fst)
. map (f &&& id)