View source code
Display the source code in std/range/package.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

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.

License

Boost License 1.0.