How Nested Functions Work, part 1

Jeremie Pelletier jeremiep at gmail.com
Wed Sep 2 09:32:43 PDT 2009


Nick Sabalausky Wrote:

> "Jeremie Pelletier" <jeremiep at gmail.com> wrote in message 
> news:h7h5i1$5mp$1 at digitalmars.com...
> >
> > While D is not the first place I see closures and nested functions, it is 
> > the first language I come across that blends delegates, closures and 
> > nested functions in a simple, elegant and intuitive manner.
> >
> 
> I almost agree. But not quite. D certainly handles much of it better than a 
> lot of languages, and the syntax of the *actual* nested functions is nice. 
> But there are still issues that bug the hell out of me.
> 
> For instance, it's fairly common for me, in D, to write a function that 
> takes a delegate and then call it with a delegate literal (anon func). But 
> out of all the times I've done that, I don't think there's been a single 
> time I haven't had to go look up the syntax. And here's why:
> 
> bool delegate(int a)
> delegate bool(int a)
> 
> Umm, yea. If you don't already know what I'm getting at with that, then...
> Quick! For each of these, valid or invalid?:
> 
> // D ////////////////////////
> void repeat(int n, void delegate(int i) dg)
> {
>     foreach(int i; 0..n)
>         dg(i);
> }
> repeat(5, delegate void(int i) { writefln("hi"); });
> //////////////////////////
> 
> And now the secondary question: Which, if any, of those instances of 
> "delegate" should be changed to "function"? (I know it's not a real serious 
> problem, but the thing is, 99.9% of the time, I don't care, and more 
> importantly, I don't *want* to care whether or not there's a scope being 
> passed around with the...whatever it is.)
> 
> So...If you could correctly, and confidently, identify the correct answers 
> without hesitation, especially on the first part, well...then you've got a 
> far better mind than I do.

The only valid syntax is up there, and you could use a simple closure instead of a delegate literal. As for function pointers, you can send a function pointer to a delegate value, the context only gets set to null and the method calls with a null "this", but calls nonetheless.

I almost only use delegates in D, since it allows functions pointers, delegates, closures and nested functions to be passed. Function pointers only allow function pointers, but are useful for C compatibility.

I almost never use delegate literals since closures can be used instead, even with a return value (works like 'auto' return values).

void foo(bool delegate() dg) {
    dg();
}
foo({return true;});




More information about the Digitalmars-d mailing list