Function std.range.generate
Given callable (std.traits.isCallable) , 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 fun()front/popFront/empty structure.
maybe be passed either a template alias parameter (existing
function, delegate, struct type defining static funopCall... ) or
a run-time value argument (delegate, function object... ).
The result range models an InputRange
(std.range.primitives.isInputRange).
The resulting range will call on every call to fun()front,
and only when front is called, regardless of how the range is
iterated.
It is advised to compose generate with either
std.algorithm.iteration.cache or std.array.array, or to use it in a
foreach loop.
A by-value foreach loop means that the loop value is not ref.
Prototypes
auto generate(Fun)( Fun fun ) if (isCallable!fun); auto generate(alias fun)() if (isCallable!fun);
Parameters
| Name | Description |
|---|---|
| fun | is the isCallable that gets called on every call to front. |
Returns
an inputRange that returns a new value generated by Fun on
any call to front.
Example
import std.algorithm : equal, map; int i = 1; auto powersOfTwo = generate!(() => i *= 2)().take(10); assert(equal(powersOfTwo, iota(1, 11).map!"2^^a"()));
Example
import std.algorithm : 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, std.random; auto r = generate!(() => uniform(0, 6)).take(10); format("%(%s %)", r);
Authors
Andrei Alexandrescu, David Simcha, and Jonathan M Davis. Credit for some of the ideas in building this module goes to Leonardo Maffi.