Pure not acting pure.

Jonathan M Davis jmdavisProg at gmx.com
Wed Jun 15 20:49:38 PDT 2011


On 2011-06-15 20:29, Charles McAnany wrote:
> Ah, so does the compiler figure out which ones are strongly and weakly pure
> and then optimize as appropriate? Is there a way to indicate that a
> function is strongly pure? Because it would seem odd to call a function
> you thought was pure and wind up with a mutated argument. -Charles

It is not odd to have a function which is pure wind up with a mutated 
argument. All pure by itself does is indicate that the function cannot access 
mutable, global variables. That's it.

Now, extra calls to a strongly pure function can be optimized out within an 
expression, because it is not possible for a strongly pure function to alter 
its arguments, and so it is guaranteed to have the same result every time that 
it is called, and it is guaranteed to have no side effects. So, yes, calls to 
strongly pure can be optimized out.

What makes the difference between a weakly pure function and a strongly pure 
function is their parameters. All of the parameters of a strongly pure 
function are either immutable or implicitly convertible to mutable. The 
parameters of a weakly pure function can be anything (just so long as they 
aren't all immutable or implicitly convertible to immutable, since that would 
make the function strongly pure). The advantage to weakly pure functions over 
impure functions (aside from the guarantee that they don't alter the state of 
any global variables) is that they can be called by other pure functions. This 
makes it possible to have strongly pure functions which call all kinds of 
useful functions which may alter their arguments, because the arguments of the 
strongly pure function are never altered, and its return value is always the 
same.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list