A inner pure function problem

bearophile bearophileHUGS at lycos.com
Mon Feb 20 05:26:20 PST 2012


This code looks interesting (maybe this code is also able to spot a bug in DMD, or it is able to show something I have not fully understood in D). Do you know if there are interesting ways to compile it?


T outer(T)(T function(in T) pure foo) pure {
    pure int inner() {
        return foo(5); // line 3
    }
    return inner();
}
int sqr(in int x) pure {
    return x * x;
}
void main() {
    assert(outer(&sqr) == 25); // line 14
}


test.d(3): Error: pure nested function 'inner' cannot access mutable data 'foo'
test.d(11): Error: template instance test.outer!(int) error instantiating



This compiles, but it's not nice:


int sqr(in int x) pure {
    return x * x;
}
immutable sqrPtr = &sqr;
auto outer(typeof(sqrPtr) foo) pure {
    pure int inner() {
        return foo(5);
    }
    return inner();
}
void main() {
    assert(outer(sqrPtr) == 25);
}

Bye and thank you,
bearophile


More information about the Digitalmars-d-learn mailing list