generate

Given callable (std.traits.isCallable) fun, create as a range whose front is defined by successive calls to fun(). This is especially useful to call function with global side effects (random functions), or to create ranges expressed as a single delegate, rather than an entire front/popFront/empty structure. fun maybe be passed either a template alias parameter (existing function, delegate, struct type defining static opCall) or a run-time value argument (delegate, function object). The result range models an InputRange (std.range.primitives.isInputRange). The resulting range will call fun() on construction, and every call to popFront, and the cached value will be returned when front is called.

  1. auto generate(Fun fun)
  2. auto generate()
    generate
    (
    alias fun
    )
    ()
    if ()

Return Value

Type: auto

an inputRange where each element represents another call to fun.

Examples

import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;

int i = 1;
auto powersOfTwo = generate!(() => i *= 2)().take(10);
assert(equal(powersOfTwo, iota(1, 11).map!"2^^a"()));
import std.algorithm.comparison : equal;

//Returns a run-time delegate
auto infiniteIota(T)(T low, T high)
{
    T i = high;
    return (){if (i == high) i = low; return i++;};
}
//adapted as a range.
assert(equal(generate(infiniteIota(1, 4)).take(10), [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]));
import std.format : format;
import std.random : uniform;

auto r = generate!(() => uniform(0, 6)).take(10);
format("%(%s %)", r);

Meta