each

Eagerly iterates over r and calls fun over each element.

If no function to call is specified, each defaults to doing nothing but consuming the entire range. r.front 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. std.parallelism.parallel.

Normally the entire range is iterated. If partial iteration (early stopping) is desired, fun needs to return a value of type std.typecons.Flag!"each" (Yes.each to continue iteration, or No.each to stop iteration).

  1. Flag!"each" each(Range r)
    template each(alias fun = "a")
    Flag!"each"
    each
    (
    Range
    )
    (
    Range r
    )
    if (
    !isForeachIterable!Range &&
    (
    isRangeIterable!Range ||
    __traits(compiles, typeof(r.front).length)
    )
    )
  2. Flag!"each" each(Iterable r)

Members

Functions

each
Flag!"each" each(Range r)
Flag!"each" each(Iterable r)

Parameters

fun

function to apply to each element of the range

r

range or iterable over which each iterates

Return Value

Yes.each if the entire range was iterated, No.each in case of early stopping.

Examples

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

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);
assert(arr.sum == 0);

// 1 ref parameter and index
arr.each!((i, ref e) => e = cast(int) i);
assert(arr.sum == 4.iota.sum);

See Also

Meta

Suggestion Box / Bug Report