each

Eagerly iterates over r and calls pred over each element.

If no predicate is specified, each will default to doing nothing but consuming the entire range. .front will be evaluated, but this can be avoided by explicitly specifying a predicate lambda with a lazy parameter.

each also supports opApply-based iterators, so it will work with e.g. std.parallelism.parallel.

template each(alias pred = "a")
void
each
(
Range
)
(
Range r
)
if (
!isForeachIterable!Range &&
(
isRangeIterable!Range ||
__traits(compiles, typeof(r.front).length)
)
)

Parameters

pred

predicate to apply to each element of the range

r

range or iterable over which each iterates

Examples

1 import std.range : iota;
2 
3 long[] arr;
4 iota(5).each!(n => arr ~= n);
5 assert(arr == [0, 1, 2, 3, 4]);
6 
7 // If the range supports it, the value can be mutated in place
8 arr.each!((ref n) => n++);
9 assert(arr == [1, 2, 3, 4, 5]);
10 
11 arr.each!"a++";
12 assert(arr == [2, 3, 4, 5, 6]);
13 
14 // by-ref lambdas are not allowed for non-ref ranges
15 static assert(!is(typeof(arr.map!(n => n).each!((ref n) => n++))));
16 
17 // The default predicate consumes the range
18 auto m = arr.map!(n => n);
19 (&m).each();
20 assert(m.empty);
21 
22 // Indexes are also available for in-place mutations
23 arr[] = 0;
24 arr.each!"a=i"();
25 assert(arr == [0, 1, 2, 3, 4]);
26 
27 // opApply iterators work as well
28 static class S
29 {
30     int x;
31     int opApply(scope int delegate(ref int _x) dg) { return dg(x); }
32 }
33 
34 auto s = new S;
35 s.each!"a++";
36 assert(s.x == 1);

See Also

Meta