Anonymous function syntax

Timon Gehr timon.gehr at gmx.ch
Wed Sep 21 15:56:46 PDT 2011


On 09/22/2011 12:47 AM, deadalnix wrote:
> Le 22/09/2011 00:29, bearophile a écrit :
>> Walter Bright:
>>
>>> D
>>> (a,b) { return a + b; }
>>
>> In D to define a true lambda you need types too:
>> auto f = (int a,int b){ return a + b; };

If you leave types away, you in fact create a function template literal. 
Interestingly those only work for templates so far. I'd like them to 
work at other places, eg when the argument types are clear from the type 
signature of a function the delegate gets passed to.

void foo(int delegate(int)){}
void main(){
     foo((a){return a;}); // this could work
}

>>
>> For D I think I'd like a syntax like:
>> { int a, int b => a + b }
>> That in some cases becomes just:
>> { a,b => a + b }
>>

Then you'd probably have map!{a => 2*a}(range);

That is very easy on the eyes. +1. What about:

void foo(int delegate(int)){}
void main(){
     foo{a=>2*a}; // ok?
}

Is binary '{' worth spending like that?


>
> That would be less readable for somebody coming from a C styled
> language. Curly braces for body and parenthesis for arguments is
> something very familiar.
>
> This makes Javascript's and D's closures the most readable for somebody
> having this background.

The delegates themselves are very readable indeed but they tend to screw 
up the readability of larger expressions that contain them. An alternate 
delegate syntax could help a great deal in these cases.



More information about the Digitalmars-d mailing list