在std.algorithm.map的结果上使用std.array.replace
所以我今天在摆弄D编程语言,就是找不到关于如何使用在std.algorithm.map的结果上使用std.array.replace,d,phobos,D,Phobos,所以我今天在摆弄D编程语言,就是找不到关于如何使用std.array.replace返回类型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
std.array.replace
返回类型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);
}
不幸的是,这不起作用。相反,它会失败,并显示以下错误消息:
main.d(15):错误:模板std.array.replace与任何函数模板声明都不匹配。候选项为:/usr/share/dmd/src/phobos/std/array.d(1652):std.array.replace(E,R1,R2)(E[]主语,R1 from,R2 to)if(isDynamicArray!(E[])和&isForwardRange!R1&&isForwardRange!R2&&hasLength!R2 | isSomeString!R2))
main.d(15):错误:模板std.array.replace(E,R1,R2)(E[]主语,R1 from,R2 to)if(isDynamicArray!(E[])&&isForwardRange!R1&&isForwardRange!R2&&(hasLength!R2 | isSomeString!R2))无法从参数类型推断模板函数!()(MapResult!(unaryFun,int[]),int,int)
std.algorithm.map
的文档中说它使用惰性求值,但即使使用std.array.array
来转换结果对我来说也不起作用
我使用的是DMD 2.064.2。
std.array.replace
对数组有效,而map
返回一个范围。要将范围转换为数组(将为所有元素分配内存),请使用array
功能
因此,您的示例变成:
return data.map!"a + 1"
.array
.replace(2, 1);
谢谢仍然在学习–D是一种有趣的语言,但我发现std.range的文档有点缺乏。可能有助于学习范围概念。