View source code
Display the source code in std/algorithm/iteration.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.algorithm.iteration.splitWhen

Splits a forward range into subranges in places determined by a binary predicate.

auto splitWhen(alias pred, Range) (
  Range r
)
if (isForwardRange!Range);

When iterating, one element of r is compared with pred to the next element. If pred return true, a new subrange is started for the next element. Otherwise, they are part of the same subrange.

If the elements are compared with an inequality (!=) operator, consider chunkBy instead, as it's likely faster to execute.

Parameters

NameDescription
pred Predicate for determining where to split. The earlier element in the source range is always given as the first argument.
r A forward range to be split.

Returns

a range of subranges of r, split such that within a given subrange, calling pred with any pair of adjacent elements as arguments returns false. Copying the range currently has reference semantics, but this may change in the future.

See also

splitter, which uses elements as splitters instead of element-to-element relations.

Example

import std.algorithm.comparison : equal;
import std.range : dropExactly;
auto source = [4, 3, 2, 11, 0, -3, -3, 5, 3, 0];

auto result1 = source.splitWhen!((a,b) => a <= b);
assert(result1.save.equal!equal([
    [4, 3, 2],
    [11, 0, -3],
    [-3],
    [5, 3, 0]
]));

//splitWhen, like chunkBy, is currently a reference range (this may change
//in future). Remember to call `save` when appropriate.
auto result2 = result1.dropExactly(2);
assert(result1.save.equal!equal([
    [-3],
    [5, 3, 0]
]));

Authors

Andrei Alexandrescu

License

Boost License 1.0.