4

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.

Community
  • 1
  • 1
Dominik Lohmann
  • 65
  • 1
  • 2
  • 5

1 Answers1

4

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);
Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114
  • Thanks. Still learning – D is an interesting language to dive into, but I find the documentation of std.range a little bit lacking. – Dominik Lohmann Dec 23 '13 at 19:15
  • 1
    [Ali Çehreli's book chapter on ranges](http://ddili.org/ders/d.en/ranges.html) may be helpful for learning range concepts. – eco Dec 23 '13 at 19:32