The OpenD Programming Language

cachedGC

Creates a random access cache for lazyly computed elements.

Return Value

Type: auto

ndslice, which is internally composed of three ndslices: original, allocated cache and allocated bit-ndslice.

Examples

import mir.ndslice.topology: cachedGC, iota, map;

int[] funCalls;

// cached lazy slice: 1 2 4 8 16
auto sl = 5.iota!int
    .map!((i) {
        funCalls ~= i;
        return 2 ^^ i;
    })
    .cachedGC;

assert(funCalls == []);
assert(sl[1] == 2); // remember result
assert(funCalls == [1]);
assert(sl[1] == 2); // reuse result
assert(funCalls == [1]);

assert(sl[0] == 1);
assert(funCalls == [1, 0]);
funCalls = [];

// set values directly
sl[1 .. 3] = 5;
assert(sl[1] == 5);
assert(sl[2] == 5);
// no function calls
assert(funCalls == []);

Cache of immutable elements

import mir.ndslice.slice: DeepElementType;
import mir.ndslice.topology: cachedGC, iota, map, as;

int[] funCalls;

// cached lazy slice: 1 2 4 8 16
auto sl = 5.iota!int
    .map!((i) {
        funCalls ~= i;
        return 2 ^^ i;
    })
    .as!(immutable int)
    .cachedGC;

static assert(is(DeepElementType!(typeof(sl)) == immutable int));

assert(funCalls == []);
assert(sl[1] == 2); // remember result
assert(funCalls == [1]);
assert(sl[1] == 2); // reuse result
assert(funCalls == [1]);

assert(sl[0] == 1);
assert(funCalls == [1, 0]);

See Also

Meta