Haskell equivalent to Scala's groupBy

后端 未结 7 1814
孤街浪徒
孤街浪徒 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条回答
  •  星月不相逢
    2021-02-02 12:53

    Specifically, the following should work:

    scalaGroupBy f = groupBy ((==) `on` f) . sortBy (comparing f)
    

    modulo that this doesn't get you the result of f in each group, but if you really need it you can always post-process with

    map (\xs -> (f (head xs), xs)) . scalaGroupBy f
    

提交回复
热议问题