Jesse Phillips wrote:
Walter Bright Wrote:
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[].
The problem is that you can't call reverse or sort unless the function is
'pure,' but the function can not be pure because it modifies its own
parameters which means his example function cannot be marked pure even though
it is.
The function in the example does not modify its parameters.