How Nested Functions Work, part 1

Nick Sabalausky a at a.a
Wed Sep 2 03:07:24 PDT 2009


"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?:

// A ////////////////////////
void repeat(int n, delegate void(int i) dg)
{
    foreach(int i; 0..n)
        dg(i);
}
repeat(5, delegate void(int i) { writefln("hi"); });

// B ////////////////////////
void repeat(int n, void delegate(int i) dg)
{
    foreach(int i; 0..n)
        dg(i);
}
repeat(5, void delegate(int i) { writefln("hi"); });

// C ////////////////////////
void repeat(int n, delegate void(int i) dg)
{
    foreach(int i; 0..n)
        dg(i);
}
repeat(5, void delegate(int i) { writefln("hi"); });

// 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.





More information about the Digitalmars-d mailing list