Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D: reduce with delegate

Tags:

d

This snippet of pseudo code works just fine:

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

In fact it appears in multiple examples and docs.

However, this does not work, and I can't figure out why:

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

I keep getting the following error:

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

I thought it might be a bug in D, but perhaps I've missed something...?

(My actual delegate is more complex, I just reduced the code to minimal example that demonstrates the problem).

like image 969
Amir Abiri Avatar asked Aug 30 '14 09:08

Amir Abiri


1 Answers

Using (a, b) => { return a + b; }, the lambda is a function/delegate that returns a function/delegate and not the result of the operation a + b. You should use (a, b) { return a + b; } without the => lambda operator to make it behave like you want.

This can be seen using the following code:

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"

So your code should be RANGE.reduce!((a, b) { return a + b; });

like image 172
yaz Avatar answered Sep 20 '22 13:09

yaz