D:用代表减少

Ami*_*iri 8 d

这段伪代码工作得很好:

RANGE.reduce!((a,b) => a + b);
Run Code Online (Sandbox Code Playgroud)

实际上它出现在多个示例和文档中.

但是,这不起作用,我无法弄清楚原因:

RANGE.reduce!((a,b) => { return a + b; });
Run Code Online (Sandbox Code Playgroud)

我一直收到以下错误:

algorithm.d(52,52): Error: cannot implicitly convert expression
    (__lambda1(result, _param_1.front()))
    of type int delegate() nothrow @nogc @safe
    to int
Run Code Online (Sandbox Code Playgroud)

我认为它可能是D中的一个错误,但也许我错过了一些东西......?

(我的实际委托更复杂,我只是将代码简化为演示问题的最小示例).

yaz*_*yaz 12

使用时(a, b) => { return a + b; },lambda是一个函数/委托,它返回一个函数/委托,而不是操作的结果a + b.您应该在(a, b) { return a + b; }没有=>lambda运算符的情况下使用它,使其表现得像您想要的那样.

使用以下代码可以看到:

pragma(msg, typeof((int a, int b) => a + b).stringof);
// prints "int function(int a, int b) pure nothrow @safe"

pragma(msg, typeof((int a, int b) => {return a + b;}).stringof);
// prints "int delegate() nothrow @safe function(int a, int b) pure nothrow @safe"

pragma(msg, typeof((int a, int b) { return a + b; }).stringof);
// prints "int function(int a, int b) pure nothrow @safe"
Run Code Online (Sandbox Code Playgroud)

所以你的代码应该是RANGE.reduce!((a, b) { return a + b; });