delegate from lambda expression

Timon Gehr timon.gehr at gmx.ch
Sun Sep 9 17:08:42 PDT 2012


On 09/10/2012 01:20 AM, 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?

Because it can't. D unfortunately does not have powerful type inference.

> 2) how to convert a lambda a=>a*2 to a delegate or function?

Those need full type information. The lambda as shown is generic.

> 3) if 2 is not possible, how to achieve what I'm trying to do WITHOUT
> having to make the type explicit as in "int delegate(int) dg=(int
> a){return a*2;}"?

template ID(alias a){ alias a ID; }

void main(){
     alias ID!(a=>a*2) dg;
     auto a=iota(0,10);
     writeln(a.map!dg.array);
}


> 4) is there a way to have template delegates, and what's the syntax in
> this simple example?
>

Already shown.



More information about the Digitalmars-d-learn mailing list