Given a list [v]
and a keying function f :: v -> k
, I want to generate a map Map k [v]
. Does something like this exist in Haskell?
import Data.Map
groupByKey :: (v -> k) -> [v] -> Map k [v]
You can use fromListWith
, like so:
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"])]
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With