Haskell equivalent to Scala's groupBy

后端 未结 7 1907
孤街浪徒
孤街浪徒 2021-02-02 12:29

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

7条回答
  •  Happy的楠姐
    2021-02-02 13:01

    Since Scala groupBy returns an immutable HashMap, which does not require ordering, the corresponding Haskell implementation should return a HashMap as well.

    import qualified Data.HashMap.Strict as M
    
    scalaGroupBy :: (Eq k, Hashable k) => (v -> k) -> [v] -> M.HashMap k [v]
    scalaGroupBy f l = M.fromListWith (++) [ (f a, [a]) | a <- l]
    

提交回复
热议问题