Thread overview
anonymous function/deleget usage
Nov 12, 2009
Sam Hu
Nov 12, 2009
Don
Nov 12, 2009
bearophile
Nov 12, 2009
Ary Borenszweig
Re: anonymous function/delegate usage
Nov 13, 2009
Sam Hu
Nov 13, 2009
BCS
Nov 13, 2009
Sam Hu
November 12, 2009
How can I reach something like below code:

int a=1;
int b=2;
int c=(int a,int b){
   return a+b;}
writefln("Result:%d",c);

Thanks in advance.
November 12, 2009
Sam Hu wrote:
> How can I reach something like below code:
> 
> int a=1;
> int b=2;
> int c=(int a,int b){
>    return a+b;}
> writefln("Result:%d",c);
> 
> Thanks in advance.

You need to call the delegate you've made.

int a=1;
int b=2;
int c=(int a,int b){
   return a+b;}(a,b);
writefln("Result:%d",c);}
November 12, 2009
On Thu, 12 Nov 2009 10:21:44 -0500, Don <nospam@nospam.com> wrote:

> Sam Hu wrote:
>> How can I reach something like below code:
>>  int a=1;
>> int b=2;
>> int c=(int a,int b){
>>    return a+b;}
>> writefln("Result:%d",c);
>>  Thanks in advance.
>
> You need to call the delegate you've made.
>
> int a=1;
> int b=2;
> int c=(int a,int b){
>     return a+b;}(a,b);
> writefln("Result:%d",c);}

Also, don't forget you can refer to variables in the enclosing function:

int c = (){return a + b;}();

-Steve
November 12, 2009
Steven Schveighoffer:

> int c = (){return a + b;}();

You can also write:
int c = {return a + b;}();

Bye,
bearophile
November 12, 2009
bearophile wrote:
> Steven Schveighoffer:
> 
>> int c = (){return a + b;}();
> 
> You can also write:
> int c = {return a + b;}();
> 
> Bye,
> bearophile

Shorter:

int c = a + b;
November 13, 2009
Don Wrote:

> You need to call the delegate you've made.

I missed this key point.

So to summary:
int a=1;
int b=2;
1.nested function;
2.int c=(int a,int b){return a+b;}(a,b);
3.int c=(int,int){return a+b;}(a,b);
4.int c=(){return a+b;}();
5.int c={return a+b;}();

How come the last one is legal?

Thank you all for all your help!
November 13, 2009
Hello Sam,

> Don Wrote:
> 
>> You need to call the delegate you've made.
>> 
> I missed this key point.
> 
> So to summary:
> int a=1;
> int b=2;
> 1.nested function;
> 2.int c=(int a,int b){return a+b;}(a,b);
> 3.int c=(int,int){return a+b;}(a,b);
> 4.int c=(){return a+b;}();
> 5.int c={return a+b;}();
> How come the last one is legal?

If the function has no args the first () can be dropped.
If the return type can be inferred, that can be dropped.
Nested functions can access vars in the outer function.

> 
> Thank you all for all your help!
> 


November 13, 2009
BCS Wrote:

> If the function has no args the first () can be dropped.
> If the return type can be inferred, that can be dropped.
> Nested functions can access vars in the outer function.
> 

Got it.Thanks a lot!