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).
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; })
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With