Haskell equivalent to Scala's groupBy

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

    This solution will break and group by on (f x), regardless wether it is sorted or not

    f = (`mod` (2::Int))
    
    list = [1,3,4,6,8,9] :: [Int]
    
    
    myGroupBy :: Eq t => (b -> t) -> [b] -> [(t, [b])]
    
    myGroupBy f (z:zs) = reverse $ foldl (g f) [(f z,[z])] zs
      where
        -- folding function                        
        g f ((tx, xs):previous) y = if (tx == ty)
                               then (tx, y:xs):previous
                               else (ty, [y]):(tx, reverse xs):previous
            where ty = f y                        
    
    main = print $ myGroupBy f list
    

    result: [(1,[1,3]),(0,[4,6,8]),(1,[9])]

    0 讨论(0)
提交回复
热议问题