Haskell GroupByKey - How to group items in a list by function?

Given the list [v]and key 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]
+4
source share
1 answer

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"])]
>
+8
source

Source: https://habr.com/ru/post/1691011/


All Articles