← All languages
Haskell function of the day
Random

groupBy

Group consecutive elements using a custom equality predicate.

Description

groupBy takes a binary predicate and a list, grouping consecutive elements that satisfy the predicate with respect to the first element of the group. Its type signature is (a -> a -> Bool) -> [a] -> [[a]]. Each sublist in the result is non-empty.

groupBy generalizes group by allowing any binary predicate instead of (==). The predicate is applied between the first element of the current group and each subsequent element. Elements are added to the group as long as the predicate holds.

groupBy is useful for grouping by equivalence classes, such as grouping numbers by sign or characters by case. It is found in Data.List. For global grouping, sort the list first and then apply groupBy.

Arguments

NameDescriptionOptional
eq A binary predicate (a -> a -> Bool) for grouping. No
xs The list [a] to group. No

Example

import Data.List (groupBy)
groupBy (==) [1, 1, 2, 2, 3]         -- [[1,1],[2,2],[3]]
groupBy (\x y -> even x == even y) [2, 4, 1, 3, 6]
-- [[2, 4], [1, 3], [6]]

Reference