Proposal: Relax rules for 'pure'

Walter Bright newshound2 at digitalmars.com
Wed Sep 22 15:03:25 PDT 2010


Steven Schveighoffer wrote:
>> 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.

No, that would be a weakly pure one.

> 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.

This isn't what I was talking about - you didn't modify the contents of the 
array x[].


More information about the Digitalmars-d mailing list