2014-08-30 40 views
8

的伪这段代码只是正常:d:减少委托

RANGE.reduce!((a,b) => a + b); 

事实上,它出现在多个实例和文档。

但是,这并不工作,我想不通为什么:

RANGE.reduce!((a,b) => { return a + b; }); 

我不断收到以下错误:

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

我想这可能是在d中的错误,但也许我错过了什么......?

(我的实际委托更加复杂,我只是将代码缩减为演示问题的最小示例)。

回答

12

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

这可以用下面的代码中可以看出:

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" 

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