View source code
Display the source code in std/algorithm/iteration.d from which thispage was generated on github.
Report a bug
If you spot a problem with this page, click here to create aBugzilla 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 usinglocal clone.

Function std.algorithm.iteration.lazyCache

Similar to cache, but lazily evaluates the elements. Unlike cache, this function does not eagerly evaluate the front of the range until it's explicitly requested.

auto lazyCache(Range)(
  Range range
)
if (isInputRange!Range);

This can be useful when evaluation of range elements has side effects that should be delayed until actually needed.

See Also

cache

Parameters

NameDescription
range an input range

Returns

An input range with the lazily cached values of range

Example

import std.algorithm.comparison : equal;
import std.range, std.stdio;
import std.typecons : tuple;

ulong counter = 0;
double fun(int x)
{
    ++counter;
    // http://en.wikipedia.org/wiki/Quartic_function
    return ( (x + 4.0) * (x + 1.0) * (x - 1.0) * (x - 3.0) ) / 14.0 + 0.5;
}
// With lazyCache, front won't be evaluated until requested
counter = 0;
auto result = iota(-4, 5).map!(a => tuple(a, fun(a)))()
                        .lazyCache();
// At this point, no elements have been evaluated yet
writeln(counter); // 0
// Now access the first element
auto firstElement = result.front;
// Only now the first element is evaluated
writeln(counter); // 1
// Process the result lazily
auto filtered = result.filter!(a => a[1] < 0)()
                     .map!(a => a[0])();
// Values are calculated as we iterate
assert(equal(filtered, [-3, -2, 2]));
// Only elements we actually accessed were evaluated
writeln(counter); // iota(-4, 5).length

Authors

Andrei Alexandrescu

License

Boost License 1.0.