On 4/9/2013 1:04 AM, Dicebot wrote:
On Tuesday, 9 April 2013 at 07:57:37 UTC, Manu wrote:
Are you saying the example above is not actually valid code?

struct Foo {
    int a = 0;
    pure int bar( int n ) { // Weakly pure
        a += n;
        return a;
    }
}

That's not pure. Call it twice with the same args, you'll different
answers. How can that possibly be considered pure in any sense?
And it's useless in terms of optimisation, so why bother at all? What does
it offer?

It is valid code. It is "weak pure". "pure' keyword means both
"strong pure" or "weak pure" depending on function body. Crap.

No, it is weakly or strongly pure based on the parameter types. bar(int n), for example, has an (implicit) mutable reference to 'this' in its parameter list. To be strongly pure, bar(int n) would have to be declared as:

    const pure int bar(int n);

What the 'pure' keyword says is: "no reads/writes to mutable data from references that do not come through the parameters." Hence, if the parameters are all const or immutable, and it is marked pure, then the function is "strongly pure", meaning "no reads/writes to any externally visible mutable state".

Notably, this is NOT determined by reading the function body, but by examining the parameter types.

The reason for this behavior is so that strongly pure functions can call weakly pure struct/class methods, and yet remain strongly pure. Purity in D would be largely useless otherwise, as very very few functions could be strongly pure.

Reply via email to