Haskell equivalent to Scala's groupBy

后端 未结 7 1880
孤街浪徒
孤街浪徒 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 13:11

    Putting a trace in f reveals that, with @Niklas solution, f is evaluated 3 times for each element on any list of length 2 or more. I took the liberty of modifying it so that f is applied to each element only once. It's not clear however whether the cost of creating and destroying tuples is less than the cost of evaluating f multiple times (since f can be arbitrary).

    import Control.Arrow ((&&&))
    import Data.List
    import Data.Function
    
    myGroupBy' :: (Ord b) => (a -> b) -> [a] -> [(b, [a])]
    myGroupBy' f = map (fst . head &&& map snd)
                       . groupBy ((==) `on` fst)
                       . sortBy (compare `on` fst)
                       . map (f &&& id)
    

提交回复
热议问题