>>> groupBy (\a b -> b - a < 5) [0..19] [[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]]It's often preferable to use Data.List.NonEmpty.groupBy, which provides type-level guarantees of non-emptiness of inner lists.
>>> groupBy (/=) [1, 1, 1, 2, 3, 1, 4, 4, 5] [[1],[1],[1,2,3],[1,4,4,5]]
>>> groupBy (>) [1, 3, 5, 1, 4, 2, 6, 5, 4] [[1],[3],[5,1,4,2],[6,5,4]]
>>> groupBy (const not) [True, False, True, False, False, False, True] [[True,False],[True,False,False,False],[True]]
>>> groupBy (<) "abcdebcdef" ["abcde","bcdef"]In contrast to that groupBy compares the head of each sublist with each candidate for this sublist. This yields
>>> List.groupBy (<) "abcdebcdef" ["abcdebcdef"]The second b is compared with the leading a. Thus it is put into the same sublist as a. The sublists are never empty. Thus the more precise result type would be [(a,[a])].
>>> groupBy (\a b -> b - a < 5) [0..19] [[0,1,2,3,4],[5,6,7,8,9],[10,11,12,13,14],[15,16,17,18,19]]It's often preferable to use Data.List.NonEmpty.groupBy, which provides type-level guarantees of non-emptiness of inner lists.
let notBoth1 a b = not (a == 1 || b == 1) in groupBy' notBoth1 [1,1,2,3,1,1,4,5,6,1] [[1],[1,2,3,1],[1,4,5,6,1]] groupBy notBoth1 [1,1,2,3,1,1,4,5,6,1] [[1],[1,2,3],[1],[1,4,5,6],[1]]In the first result the list is split anywhere there are two adjacent ones, as desired.
> classifyBy (\(x,_) (y,_) -> x == y) [(1,1),(1,2),(2,1),(2,2)] [[(1,1),(1,2)],[(2,1),(2,2)]](cf. classify, classifyOn)
groupBy' (\a b -> abs (a - b) <= 1) [1,2,3] = [[1,2,3]]whereas
groupBy (\a b -> abs (a - b) <= 1) [1,2,3] = [[1,2],[3]]TODO: Check in ghc 6.12 release if groupBy == groupBy'.