group package:protolude

The group function takes a list and returns a list of lists such that the concatenation of the result is equal to the argument. Moreover, each sublist in the result is non-empty and all elements are equal to the first one. group is a special case of groupBy, which allows the programmer to supply their own equality test. It's often preferable to use Data.List.NonEmpty.group, which provides type-level guarantees of non-emptiness of inner lists.

Examples

>>> group "Mississippi"
["M","i","ss","i","ss","i","pp","i"]
>>> group [1, 1, 1, 2, 2, 3, 4, 5, 5]
[[1,1,1],[2,2],[3],[4],[5,5]]
The groupBy function is the non-overloaded version of group. When a supplied relation is not transitive, it is important to remember that equality is checked against the first element in the group, not against the nearest neighbour:
>>> 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.

Examples

>>> 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]]
The class of semigroups (types with an associative binary operation). Instances should satisfy the following:
  • Associativity x <> (y <> z) = (x <> y) <> z
You can alternatively define sconcat instead of (<>), in which case the laws are: