Haskell groupBy function: How exactly does it work?

Viewed 3796

I experienced the following behavior:

ghci :m +Data.List

ghci> groupBy (\x y -> succ x == y) [1..6]
[[1,2], [3,4], [5,6]]
ghci> groupBy (\x y -> succ x /= y) [1..6]
[[1], [2], [3], [4], [5], [6]]

ghci :m +Data.Char   -- just a test to verify that nothing is broken with my ghc

ghci> groupBy (const isAlphaNum) "split this"
["split"," this"]

which surprised me, I thought, based on the example down below, that groupBy splits a list whenever the predicate evaluates to True for two successive elements supplied to a predicate. But in my second example above it splits the list on every element, but the predicate should evaluate to False. I framed my assumption of how it works in Haskell as well, just so everybody understands how I believed it to work:

groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy p l@(x:y:ys)
  | p x y     = (x:y:(head l)) ++ (tail l)       -- assuming l has a tail, unwilling to
  | otherwise = [x] ++ (y:(head l)) ++ (tail l)  -- to debug this right now, I guess you
groupBy _ [x] = [[x]]                            -- already got the hang of it ;)

Which brought me to the conclusion, that it works somewhat different. So my question is, how does that function actually work?

1 Answers
Related