delegate from lambda expression
Jacob Carlborg
doob at me.com
Mon Sep 10 00:08:13 PDT 2012
On 2012-09-10 01:20, timotheecour wrote:
> I'd like to achieve the following:
> ----
> import std.stdio,std.range,std.algorithm,std.array;
> void main(){
> auto dg=a=>a*2;
> auto a=iota(0,10);
> writeln(a.map!dg.array);
> }
> ----
> but this doesn't compile:
> Error: variable [...]dg type void is inferred from initializer delegate
> (__T26 a)
> {
> return a * 2;
> }
> , and variables cannot be of type void
>
> However this works:
> writeln(a.map!(a=>a*2).array);
> but I want to reuse dg in other expressions (and avoid repeating myself)
> Also, I want to avoid using string litteral enum dg=`a*2` as in my case
> dg is much more complicated and this is cleaner without a string IMHO.
>
> My questions:
> 1) why can't the compiler infer the type int(int) for dg?
> 2) how to convert a lambda a=>a*2 to a delegate or function?
Try this:
auto dg = (int a) => a * 2;
If that doesn't work, this should:
auto dg = (int a) { return a * 2; };
--
/Jacob Carlborg
More information about the Digitalmars-d-learn
mailing list