# GroupBy proposal

From HaskellWiki

Revision as of 17:51, 10 January 2007 by JohannesAhlmann (talk | contribs)

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...