Nested function declarations

bearophile bearophileHUGS at lycos.com
Thu Jan 27 16:03:57 PST 2011


> What is the purpose of nested function declarations in D? Is it a good idea to just disallow them?

In theory they may be used to define mutually recursive nested functions, like in this example, but in practice this is not allowed:

import std.stdio: writeln;

void main() {
    // Hofstadter Female and Male sequences
    int M(int);

    int F(int n) {
        return n ? n - M(F(n - 1)) : 1;
    }

    int M(int n) { // test.d(11): Error: declaration M is already defined
        return n ? n - F(M(n - 1)) : 0;
    }

    foreach (i; 0 .. 100)
        writeln(F(i));
}

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list