The OpenD Programming Language

each

Eagerly iterates over r and calls fun with 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

import std.range : iota;
import std.typecons : No;

int[] arr;
iota(5).each!(n => arr ~= n);
assert(arr == [0, 1, 2, 3, 4]);

// stop iterating early
iota(5).each!((n) { arr ~= n; return No.each; });
assert(arr == [0, 1, 2, 3, 4, 0]);

// If the range supports it, the value can be mutated in place
arr.each!((ref n) => n++);
assert(arr == [1, 2, 3, 4, 5, 1]);

arr.each!"a++";
assert(arr == [2, 3, 4, 5, 6, 2]);

auto m = arr.map!(n => n);
// by-ref lambdas are not allowed for non-ref ranges
static assert(!__traits(compiles, m.each!((ref n) => n++)));

// The default predicate consumes the range
(&m).each();
assert(m.empty);

each can pass an index variable for iterable objects which support this

auto arr = new size_t[4];

arr.each!"a=i"();
assert(arr == [0, 1, 2, 3]);

arr.each!((i, ref e) => e = i * 2);
assert(arr == [0, 2, 4, 6]);

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++";
assert(s.x == 1);

See Also

Meta