[Haskell-beginners] Is it possible to implement groupBy using folds?

Stephen Tetley stephen.tetley at gmail.com
Thu Jun 16 16:36:38 CEST 2011


This foldr version uses a partitioned accumulator and a
post-processing step - it should be possible to achieve the same with
an accumulator of [[a]] and deeper pattern matching:


groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy test = post . foldr fn ([],[])
  where
    post ([],yss) = yss
    post (xs,yss) = xs : yss

    fn a ([],yss)                = ([a], yss)
    fn a (b:bs, yss) | test a b  = (a:b:bs, yss)
                     | otherwise = ([a], (b:bs):yss)



More information about the Beginners mailing list