about lambdas

Timon Gehr timon.gehr at gmx.ch
Thu Jan 3 14:20:41 PST 2013


On 01/03/2013 10:54 PM, Michael wrote:
> Thanks guys)
>
>>
>> auto With(alias fun, I)(I o) // maybe add a template constraint here
>> {
>>     static if(isAssignable!(I, typeof(null)))
>>         return o is null ? null : fun(o);
>>     else
>>         return fun(o);
>> }
>>
>> foreach(p; persons)
>>     p.With!(x => x.address);
>>
>
> Now if I want add a somewhat task into expression "x => x.address", for
> example "writeln(x.address)", a code should be rewritten like
>
>>
>> foreach(p; persons)
>>     p.With!(x => {writeln(x.address); return x.address;}());
>>
>
> As I understand, right part of expression above - "{ ... }()" is
> anonymous function (or delegate, or closure) that immediately called in
> lambda expression. Right? Is right behaviour?

You understand this correctly, but it is a somewhat roundabout way to 
achieve what you want to do.

This should work as well:

foreach(p; persons)
     p.With!((x){writeln(x.address); return x.address;});

The reason is that there are two different ways for forming function 
literals. The lambda literal a=>exp is immediately rewritten to (a){ 
return exp; }

Historically, the lambda syntax has not been available, turning function 
literal heavy code into something that looked like
{return{return(){return((){return}())}. The introduction of '=>' was a 
backwards-compatible addition.



More information about the Digitalmars-d mailing list