bearophile wrote:
Jonathan M Davis:

I assume that if you declare a member function as pure, then all of its parameters - including the invisible this - are included in that. That is, if all of them - including the invisible this - have the same value, then the result will be the same.

This D2 program runs with no errors, and here there isn't a D language/compiler 
bug:

struct Foo {
    int x;
    this (int xx) { this.x = xx; }
    pure int bar() { return x; }
}
void main() {
    Foo f = Foo(1);
    assert(f.bar() == 1);
    f.x *= 2;
    assert(f.bar() == 2);
}

Bye,
bearophile

You do need to be careful about concluding how 'pure' works based on the current behaviour of the compiler. There's a trap here. What if you use a hypothetical startTimer() function which executes a delegate every few clock ticks?

void main() {
    Foo f = Foo(1);
    startTimer( () { f.x++; });
    scope(exit)
        killTimer();

    assert(f.bar() == 1); // may fail!
    f.x *= 2;
    assert(f.bar() == 2);
}

I actually think that 'pure' on a member function can only mean, it's cacheably pure if and only if 'this' can be cast to immutable. Which includes the important case where the call is made from a pure function (this implies that the 'this' pointer is either a local variable of a pure function, or an immutable object). Since pure functions cannot call impure functions, they can't do any of this nasty asynchronous stuff.

In fact I think in general, that's how pure should work: once you're inside 'pure', you should be able to pass even mutable objects into pure functions. This is possible because although it's mutable, the entire code that modifies it is confined to a single function. So the compiler can determine if it is cacheably pure without performing any kind of whole program analysis.

But this is just my opinion. I don't know if it will eventually work that way.

Reply via email to