You can use fromListWith
, for example:
import Data.Map
groupByKey :: (Ord k) => (v -> k) -> [v] -> Map k [v]
groupByKey getkey
= fromListWith (++) . fmap (\val -> (getkey val, [val]))
so that:
> groupByKey length $ words "hello there my good friend"
fromList [(2,["my"]),(4,["good"]),(5,["there","hello"]),(6,["friend"])]
>
source
share