sliceBy

Slices an input array into slices of equivalent adjacent elements. In other languages this is often called partitionBy, groupBy or sliceWhen.

Equivalence is defined by the predicate pred, which can be binary, which is passed to std.functional.binaryFun. Two range elements a and b are considered equivalent if pred(a,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 sliceBy may assert at runtime or behave erratically.

sliceBy
pure nothrow
(
alias pred
Array
)
(
Array array
)
if (
isDynamicArray!Array
)

Parameters

pred

Predicate for determining equivalence.

Return Value

Type: auto

With a binary predicate, a range of slices is returned in which all elements in a given slice are equivalent under the given predicate.

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.

Examples

1 import std.algorithm.comparison : equal;
2 
3 // Grouping by particular attribute of each element:
4 auto data = [
5     [1, 1],
6     [1, 2],
7     [2, 2],
8     [2, 3]
9 ];
10 
11 auto r1 = data.sliceBy!((a,b) => a[0] == b[0]);
12 assert(r1.equal([
13     data[0 .. 2],
14     data[2 .. 4]
15 ]));
16 
17 auto r2 = data.sliceBy!((a,b) => a[1] == b[1]);
18 assert(r2.equal([
19     data[0 .. 1],
20     data[1 .. 3],
21     data[3 .. 4],
22 ]));

Meta