Function std.range.generate
Given callable (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
(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.
auto generate(Fun)
(
Fun fun
)
if (isCallable!fun);
auto generate(alias fun)()
if (isCallable!fun);
Returns
an inputRange
where each element represents another call to fun.
Example
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"()));
Example
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]));
Example
import std .format : format;
import std .random : uniform;
auto r = generate!(() => uniform(0, 6)) .take(10);
format("%(%s %)", r);
Authors
Andrei Alexandrescu, David Simcha, Jonathan M Davis, and Jack Stouffer. Credit for some of the ideas in building this module goes to Leonardo Maffi.