# Difference between revisions of "GroupBy proposal"

From HaskellWiki

BrettGiles (talk | contribs) m (GroupBy Proposal moved to GroupBy proposal) |
RossPaterson (talk | contribs) (moved into List_function_suggestions) |
||

Line 1: | Line 1: | ||

− | [[Category:Proposals]] |
||

+ | 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: |
||

− | |||

− | <haskell> |
||

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

− | [[1,2],[3,4],[6]] |
||

− | </haskell> |
||

− | |||

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

− | |||

− | <haskell> |
||

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

− | [[1,2,3,4],[6]] |
||

− | </haskell> |
||

− | |||

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

− | |||

− | <haskell> |
||

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

− | </haskell> |
||

− | |||

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