Template std.algorithm.iteration.each
Eagerly iterates over r
and calls fun
over each element.
template each(alias fun)
;
If no function to call is specified, each
defaults to doing nothing but
consuming the entire range. r
will be evaluated, but that can be avoided
by specifying a lambda with a lazy
parameter.
each
also supports opApply
-based types, so it works with e.g. parallel
.
Normally the entire range is iterated. If partial iteration (early stopping) is
desired, fun
needs to return a value of type std
!"each"
(Yes
to continue iteration, or No
to stop
iteration).
Contained Functions
Name | Description |
---|---|
each |
Parameters
Name | Description |
---|---|
fun | function to apply to each element of the range |
r | range or iterable over which each iterates |
Returns
Yes
if the entire range was iterated, No
in case of early
stopping.
See Also
std
Example
import std .range : iota;
import std .typecons : Flag, Yes, No;
long[] arr;
iota(5) .each!(n => arr ~= n);
writeln(arr); // [0, 1, 2, 3, 4]
iota(5) .each!((n) { arr ~= n; return No .each; });
writeln(arr); // [0, 1, 2, 3, 4, 0]
// If the range supports it, the value can be mutated in place
arr .each!((ref n) => n++);
writeln(arr); // [1, 2, 3, 4, 5, 1]
arr .each!"a++";
writeln(arr); // [2, 3, 4, 5, 6, 2]
// by-ref lambdas are not allowed for non-ref ranges
static assert(!is(typeof(arr .map!(n => n) .each!((ref n) => n++))));
// The default predicate consumes the range
auto m = arr .map!(n => n);
(&m) .each();
assert(m .empty);
// Indexes are also available for in-place mutations
arr[] = 0;
arr .each!"a=i"();
writeln(arr); // [0, 1, 2, 3, 4, 5]
// opApply iterators work as well
static class S
{
int x;
int opApply(scope int delegate(ref int _x) dg) { return dg(x); }
}
auto s = new S;
s .each!"a++";
writeln(s .x); // 1
Example
each
works with iterable objects which provide an index variable, along with each element
import std .range : iota, lockstep;
auto arr = [1, 2, 3, 4];
// 1 ref parameter
arr .each!((ref e) => e = 0);
writeln(arr .sum); // 0
// 1 ref parameter and index
arr .each!((i, ref e) => e = cast(int) i);
writeln(arr .sum); // 4.iota.sum