Function std.algorithm.iteration.chunkBy
Chunks an input range into subranges of equivalent adjacent elements.
In other languages this is often called partitionBy
, groupBy
or sliceWhen
.
auto chunkBy(alias pred, Range)
(
Range r
)
if (isInputRange!Range);
Equivalence is defined by the predicate pred
, which can be either
binary, which is passed to binaryFun
, or unary, which is
passed to unaryFun
. In the binary form, two range elements
a
and b
are considered equivalent if pred(a,b)
is true. In
unary form, two elements are considered equivalent if pred(a) == pred(b)
is true.
This predicate must be an equivalence relation, that is, it must be
reflexive (pred(x,x)
is always true), symmetric
(pred(x,y) == pred(y,x)
), and transitive (pred(x,y) && pred(y,z)
implies pred(x,z)
). If this is not the case, the range returned by
chunkBy may assert at runtime or behave erratically.
Parameters
Name | Description |
---|---|
pred | Predicate for determining equivalence. |
r | An input range to be chunked. |
Returns
With a binary predicate, a range of ranges is returned in which all elements in a given subrange are equivalent under the given predicate. With a unary predicate, a range of tuples is returned, with the tuple consisting of the result of the unary predicate for each subrange, and the subrange itself.
Notes
Equivalent elements separated by an intervening non-equivalent element will appear in separate subranges; this function only considers adjacent equivalence. Elements in the subranges will always appear in the same order they appear in the original range.
See also
group
, which collapses adjacent equivalent elements into a single
element.
Example
Showing usage with binary predicate:
import std .algorithm .comparison : equal;
// Grouping by particular attribute of each element:
auto data = [
[1, 1],
[1, 2],
[2, 2],
[2, 3]
];
auto r1 = data .chunkBy!((a,b) => a[0] == b[0]);
assert(r1 .equal!equal([
[[1, 1], [1, 2]],
[[2, 2], [2, 3]]
]));
auto r2 = data .chunkBy!((a,b) => a[1] == b[1]);
assert(r2 .equal!equal([
[[1, 1]],
[[1, 2], [2, 2]],
[[2, 3]]
]));
Example
Showing usage with unary predicate:
import std .algorithm .comparison : equal;
import std .range .primitives;
import std .typecons : tuple;
// Grouping by particular attribute of each element:
auto range =
[
[1, 1],
[1, 1],
[1, 2],
[2, 2],
[2, 3],
[2, 3],
[3, 3]
];
auto byX = chunkBy!(a => a[0])(range);
auto expected1 =
[
tuple(1, [[1, 1], [1, 1], [1, 2]]),
tuple(2, [[2, 2], [2, 3], [2, 3]]),
tuple(3, [[3, 3]])
];
foreach (e; byX)
{
assert(!expected1 .empty);
writeln(e[0]); // expected1.front[0]
assert(e[1] .equal(expected1 .front[1]));
expected1 .popFront();
}
auto byY = chunkBy!(a => a[1])(range);
auto expected2 =
[
tuple(1, [[1, 1], [1, 1]]),
tuple(2, [[1, 2], [2, 2]]),
tuple(3, [[2, 3], [2, 3], [3, 3]])
];
foreach (e; byY)
{
assert(!expected2 .empty);
writeln(e[0]); // expected2.front[0]
assert(e[1] .equal(expected2 .front[1]));
expected2 .popFront();
}