Haskell equivalent to Scala's groupBy

后端 未结 7 1803
孤街浪徒
孤街浪徒 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:55

    You can write the function yourself rather easily, but you need to place an Ord or Hashable constraint on the result of the classifier function if you want an efficient solution. Example:

    import Control.Arrow ((&&&))
    import Data.List
    import Data.Function
    
    myGroupBy :: (Ord b) => (a -> b) -> [a] -> [(b, [a])]
    myGroupBy f = map (f . head &&& id)
                       . groupBy ((==) `on` f)
                       . sortBy (compare `on` f)
    
    > myGroupBy (`mod` 2) [1..9]
    [(0,[2,4,6,8]),(1,[1,3,5,7,9])]      
    

    You can also use a hash map like Data.HashMap.Strict instead of sorting for expected linear time.

提交回复
热议问题