group package:relude

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, all elements are equal to the first one, and consecutive equal elements of the input end up in the same element of the output list. 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. A common idiom to squash repeating elements map head . group is better served by map Data.List.NonEmpty.head . Data.List.NonEmpty.group because it avoids partial functions.

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]]
Polymorphic grouping functions.
Groups elements using results of the given function as keys.
>>> groupBy even [1..6] :: HashMap Bool (NonEmpty Int)
fromList [(False,5 :| [3,1]),(True,6 :| [4,2])]
Similar to groupBy but keeps only one element as value.
>>> groupOneBy even [1 .. 6] :: HashMap Bool Int
fromList [(False,1),(True,2)]
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: @since base-4.9.0.0