Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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]
like image 938
pathikrit Avatar asked Jan 29 '23 00:01

pathikrit


1 Answers

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"])]
>
like image 107
K. A. Buhr Avatar answered Feb 09 '23 00:02

K. A. Buhr