Syntax question about inlined functions/delegates/lambdas

Ali Çehreli acehreli at yahoo.com
Mon Dec 30 11:22:04 PST 2013


On 12/30/2013 11:00 AM, Gordon wrote:
> Hello,
>
> I have a syntax question regarding the correct usage of
> function/delegates/lambdas, arising after a used it incorrectly and it
> took a long time to debug and see what's going on.
> I found out there's a syntax which compiles OK but doesn't work (as I
> naively expected).
>
> The following is a concise example:
> ===
> import std.stdio;
> import std.functional;
>
> void call_function(FUNC...)()
> {
>          alias unaryFun!FUNC _Fun;
>          _Fun(42);
> }
>
> void main()
> {
>          call_function!( function(x)    { writeln("funcion,  case 1. X =
> ",x); } )();
>          call_function!( function(x) => { writeln("funcion,  case 2. X =
> ",x); } )();
>          call_function!( delegate(x)    { writeln("delegate, case 3. X =
> ",x); } )();
>          call_function!( delegate(x) => { writeln("delegate, case 4. X =
> ",x); } )();
>          call_function!( (x)            { writeln("funcion,  case 5. X =
> ",x); } )();
>          call_function!( (x)         => { writeln("lambda,   case 6. X =
> ",x); } )();
>          call_function!( (x)         =>   writeln("lambda,   case 7. X =
> ",x)    )();
> }
> ===
>
> The output is:
> ===
> $ rdmd ./delegate_question.d
> funcion,  case 1. X = 42
> delegate, case 3. X = 42
> funcion,  case 5. X = 42
> lambda,   case 7. X = 42
> ===
>
> So I've learned that syntaxes in cases 2,4,6 are wrong, but they still
> compile.
> May question is - what do they do? what usage do they have (since they
> do not trigger a compilation warning)?
>
> Thanks,
>   -gordon
>

(Note: This thread is more suited to the D.learn newsgroup.)

Once we move the incompatible ones away, the function literals work as 
expected:

import std.stdio;
import std.functional;

void call_function(FUNC...)()
{
     foreach (func; FUNC) {
         auto f = func(42);
         f();
     }
     // alias unaryFun!FUNC _Fun;
     // _Fun(42);
}

void main()
{
     // call_function!( function(x)    { writeln("funcion,  case 1. X = 
",x); } )();
     call_function!( function(x) => { writeln("funcion,  case 2. X = 
",x); } )();
     // call_function!( delegate(x)    { writeln("delegate, case 3. X = 
",x); } )();
     call_function!( delegate(x) => { writeln("delegate, case 4. X = 
",x); } )();
     // call_function!( (x)            { writeln("funcion,  case 5. X = 
",x); } )();
     call_function!( (x)         => { writeln("lambda,   case 6. X = 
",x); } )();
     // call_function!( (x)         =>   writeln("lambda,   case 7. X = 
",x)    )();
}

The output:

funcion,  case 2. X = 42
delegate, case 4. X = 42
lambda,   case 6. X = 42

Ali



More information about the Digitalmars-d mailing list