GroupBy proposal

From HaskellWiki
Revision as of 02:30, 29 June 2007 by BrettGiles (talk | contribs) (GroupBy Proposal moved to GroupBy proposal)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.


I was a bit annoyed when I found out that Data.List.groupBy compared each new element to the first element of a group instead of the last added element.

I guess the current way it is easier to implement, but severely hinders its usefulness:

> groupBy (\a b -> a+1 == b) [1,2,3,4,6]
[[1,2],[3,4],[6]]

I propose a different implementation of groupBy which would result in the following:

> groupBy (\a b -> a+1 == b) [1,2,3,4,6]
[[1,2,3,4],[6]]

The following a naive implementation that was written for "workiness" instead of speed or space behavior:

groupBy' :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy' _ []     = []
groupBy' f (x:xs) = gb f xs [[x]]
    where gb f (x:xs) ((a:as):bs) = gb f xs $ if f a x then ((x:a:as):bs)
                                                       else ([x]:(a:as):bs)
          gb _ []     as = reverse . map reverse $ as

I'm sure there are much nicer ways to implement this...