How Nested Functions Work, part 1

Jarrett Billingsley jarrett.billingsley at gmail.com
Wed Sep 2 06:05:42 PDT 2009


On Wed, Sep 2, 2009 at 6:07 AM, Nick Sabalausky<a at a.a> wrote:

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

Only valid one! I've been doing this too long ;)

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

Well repeat should probably always take a delegate since most likely,
you're going to be passing it a lambda. However I agree that it would
be very, very nice to be able to make APIs take just delegates and
allow functions to be implicitly cast to them. You can already make
your own thunks, but they're not going to be as efficient as something
that actually works on an ABI level.



More information about the Digitalmars-d mailing list