View source code Display the source code in std/range.d from which this page was generated on github. 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. Page wiki View or edit the community-maintained wiki page associated with this page.

Function std.range.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 every call to 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

NameDescription
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.

License

Boost License 1.0.

Comments