Question

So I was fiddling around with the D Programming Language today and just could not find any information about how to use std.array.replace on the return type of std.algorithm.map

void main() {
    import std.stdio : writeln;

    writeln(test([1, 2, 3])); // desired result: [1, 3, 4]
}

auto test(int[] data) {
    import std.algorithm : map;
    import std.array : replace;

    return data.map!"a + 1"
               .replace(2, 1);
}

Unfortunately, this does not work. Instead, it fails with the following error message:

main.d(15): Error: template std.array.replace does not match any function template declaration. Candidates are: /usr/share/dmd/src/phobos/std/array.d(1652): std.array.replace(E, R1, R2)(E[] subject, R1 from, R2 to) if (isDynamicArray!(E[]) && isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2))

main.d(15): Error: template std.array.replace(E, R1, R2)(E[] subject, R1 from, R2 to) if (isDynamicArray!(E[]) && isForwardRange!R1 && isForwardRange!R2 && (hasLength!R2 || isSomeString!R2)) cannot deduce template function from argument types !()(MapResult!(unaryFun, int[]), int, int)

The documentation of std.algorithm.map says that it uses lazy evaluation, but even using std.array.array to convert the result does not work for me.

I am using DMD 2.064.2.

Was it helpful?

Solution

std.array.replace works on arrays, whereas map returns a range. To convert the range to an array (which will allocate memory for all elements), use the array function.

Thus, your example becomes:

return data.map!"a + 1"
           .array
           .replace(2, 1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top