initializer for array of function literals

spir denis.spir at
Sun Oct 31 03:32:37 PDT 2010

On Sat, 30 Oct 2010 23:13:18 -0400
bearophile <bearophileHUGS at> wrote:

> Adrian Matoga:
> > I would appreciate if somebody explained to me why this code:
> > 
> > static void function(int a)[] foo = [ function (int a) { } ];
> > 
> > causes the following compile error:
> > 
> > test.d(2): Error: non-constant expression __funcliteral1
> When you ask for questions like these, please if possible show a complete compilable program that includes a main().
> This doesn't compile:
> static void function(int a)[] foo = [function (int a) {}];
> void main() {}
> This works, but I don't know/remember what's the difference:
> void f1(int a) {}
> static void function(int a)[] foo = [&f1];
> void main() {}

(Note: no need to name parameters in func types.)

Upon func literals, to, I don't understand why this doesn't compile:

int hof(int function(int i) f , int i) {return f(i) ;}
void main () {
    writeln( hof((int i) {return ++i ;} , 1) );

Element.d(15): Error: function Element.hof (int function(int i) mapFunc, int i) is not callable using argument types (int delegate(int i),int)
Element.d(15): Error: cannot implicitly convert expression (__dgliteral1) of type int delegate(int i) to int function(int i)

According to "the D programming language", D is supposed to construct a function when the definition does not use any variable of its environment (read: if the closure holds no upvalue); as opposed a so-called delegate (*). In this case, it's clear that "(int i) {return ++i ;}" does not close over anything, isn't it? So why does D construct a delegate anyway?

Also, I think D should not annoy us with the func/delegate distinction -- which is only for saving space -- and accept func defs that match the given type signature. The annoying distinction is semantically irrelevant; the signature is relevant.


(*) By the way, why does D call closures "delegates"? I find this very misleading, since delegation already has some meaning in the context of programming. And well, "closure" is well established precisely in this sense. Sometimes, PL designers amaze me ;-)

-- -- -- -- -- -- --
vit esse estrany ☣

More information about the Digitalmars-d-learn mailing list