Purity
Steven Schveighoffer
schveiguy at yahoo.com
Fri Dec 17 05:57:36 PST 2010
On Fri, 17 Dec 2010 02:42:14 -0500, bearophile <bearophileHUGS at lycos.com>
wrote:
> http://www.reddit.com/r/programming/comments/enajl/purity_in_d_language/
>
> Bye,
> bearophile
This is a good post, you sort of lost me at the SPARK example, but I want
to particularly note some inaccuracies that you have.
At one point you have an example that creates memory, and say that two
different calls to create memory with the same size could return the same
array. This is not valid, you introduce an aliasing issue by optimizing.
Only if the return is immutable can you do this.
Another inaccuracy (really an omission) is that a weakly pure function is
just like a pure function but cannot be memoized. In fact, it cannot be
optimized in any way like strongly pure functions can. In fact, a weakly
pure function is exactly like a normal function except it can only call
pure functions, it can be called by a pure function (strong or weak), and
it cannot access mutable globals.
In particular, a function like this:
pure int foo(ref int x) {return ++x;}
cannot be factored or reordered, i.e. this doesn't work:
foo(x) + foo(x) => 2 * foo(x)
If you think about it, you can see why.
This actually ties together nicely with my first point -- a pure function
that returns a mutable pointer must be weakly pure. Your example which
returns an int[] is returning such a pointer, so it is weakly pure.
Therefore, this is why your example that creates memory cannot return the
same array twice (that memoization optimization cannot legally be done).
-Steve
More information about the Digitalmars-d
mailing list