Function Literals

Daniel Keep daniel.keep.lists at gmail.com
Tue Mar 13 19:52:12 PDT 2007



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

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.

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; } );

	-- Daniel

-- 
Unlike Knuth, I have neither proven or tried the above; it may not even
make sense.

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/



More information about the Digitalmars-d mailing list