On Wed, 22 Sep 2010 15:36:34 -0400, Walter Bright <newshou...@digitalmars.com> wrote:

Don wrote:
Don wrote:
The docs currently state that:

PROPOSAL:
Drop the first requirement. Only one requirement is necessary:

A pure function does not read or write any global mutable state.

Wow. It seems that not one person who has responded so far has understood this proposal! I'll try again. Under this proposal: If you see a function which has mutable parameters, but is marked as 'pure', you can only conclude that it doesn't use global variables. That's not much use on it's own. Let's call this a 'weakly-pure' function. However, if you see a function maked as 'pure', which also has only immutable parameters, you have the same guarantee which 'pure' gives us as the moment. Let's call this a 'strongly-pure' function. The benefit of the relaxed rule is that a strongly-pure function can call a weakly-pure functions, while remaining strongly-pure.
This allows very many more functions to become strongly pure.
The point of the proposal is *not* to provide the weak guarantee. It is to provide the strong guarantee in more situations.

A pure function also cannot modify any data via its parameters. In other words, its parameters must be transitively const.

Yes, a strongly pure function must have those traits.

But, purity exists to allow for optimization. A weakly pure function cannot be optimized anymore than a normal function, but a strongly pure can still be optimized even if it calls weakly-pure functions.

I'll give you an example (with a new keyword to help you understand the difference):

weaklypure void reverse(int[] x)
{
   for(int i = 0; i * 2 < x.length; i++)
       swap(x[i], x[$-1-i]);
}

pure int foo(const(int)[] x)
{
    auto x2 = x.dup;
    reverse(x2);
    // do some calculation on x2
    ...
    return calculation;
}

Hopefully you can see how foo still is pure, while being able to call reverse. Essentially, weakly-pure functions can be used to build strongly-pure functions.

-Steve

Reply via email to