Difference between revisions of "GroupBy proposal"

From HaskellWiki
Jump to: navigation, search
(moved into List_function_suggestions)
(One intermediate revision by one other user not shown)
Line 1: Line 1:
see [[List function suggestions]].
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]
I propose a different implementation of groupBy which would result in the following:
> groupBy (\a b -> a+1 == b) [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...

Latest revision as of 09:57, 6 September 2007