Function Literals

janderson askme at me.com
Tue Mar 13 22:57:30 PDT 2007


Daniel Keep wrote:
> 
> Falk Henrich wrote:
>> Hi!
>>
>> I'm just experimenting with delegates and came across
>>
>> http://www.digitalmars.com/d/expression.html#FunctionLiteral
>>
>> where one finds this example:
>>
>> int abc(int delegate(long i));
>> void test()
>> {   int b = 3;
>>     abc( (long c) { return 6 + b; } );
>> }
>>
>> My question is: If the compiler can infer the return type of the anonymous function, how come it can't infer the type of the parameter c? Forgive me if this is too stupid a question, but I thought: if the compiler knows the signature of abc it has to be clear that c is of type long.
>>
>> Is it possible to simulate a syntax like
>>
>> abc( (c) { return 6+b; } );
>>
>> using templates / mixins?
>>
>> Thanks for the advice!
>>
>> Falk
> 
> This is purely speculation, however:
> 
> All the type inference that D does thus far seems to be "inside-out",
> that is it uses the known type of inner expressions to determine the
> type of the ones they're contained in.  Deriving the type of 'c' up
> there would mean the system would have to work backwards; and things
> could get messy :P

I'm not familiar with the compiler, so I'll just have to believe thats true.

> 
> Secondly, (c) looks like a C-style cast, and D doesn't like C-style
> casts.  In fact, last time I checked, it spat the dummy if you use a
> C-style cast.

While the other points seem valid.  A syntax change to:

abc( (auto c) { return 6+b; } );

could be about as useful without it looking like a C-style cast.

> 
> Thirdly, it could be that it's possible, but an awful lot of work, and
> Walter doesn't see that it's worth it.  Given that we recently got
> compile-time function evaluation, I'd agree with him :)
> 
> You also ask if it's possible to simulate the syntax using
> templates/mixins.  I'd dare say it would be, but it would probably end
> up being far more typing than it's worth:
> 
>> abc( mixin(infer(&abc, "(c) { return 6+b; }")) );
> 
> As an example, compared to
> 
>> abc( (long c) { return 6+b; } );
> 

Very true.  Although depending on the problem sometimes it can be 
re-designed to use templates instead of delegates.

> 	-- Daniel
> 



More information about the Digitalmars-d mailing list