Pure Factory Functions 💔 `inout`

ag0aep6g anonymous at example.com
Fri Feb 10 19:33:26 UTC 2023


On Friday, 10 February 2023 at 18:01:56 UTC, Steven Schveighoffer 
wrote:
> I thought strong purity had to do with call 
> elision/memoization. Clearly, calling with a const pointer 
> can't be elided or memoized if passed a mutable.
>
> So the spec is consistent I guess, I just misunderstood what 
> constituted "strong" purity.
>
> However, the Optimization section does state:
>
>        An implementation may assume that a strongly pure 
> function that returns a result without mutable indirections 
> will have the same effect for all invocations with equivalent 
> arguments. It is allowed to memoize the result of the function 
> under the assumption that equivalent parameters always produce 
> equivalent results."
>
> I feel like this is not a sound assumption if the parameter is 
> const, and the argument is mutable. Of course, if the compiler 
> can prove that the variable doesn't change elsewhere, then it's 
> OK to memoize. But just assuming because it's strong pure is 
> not correct.
>
> Of course, it depends on the definition of "equivalent 
> arguments".

In my experience, David Nadlinger's "Purity in D"[1] is a better 
source of truth than DMD or the spec when it comes to `pure`.

As far as I can tell, the spec and "Purity in D" use the same 
definitions for "weakly pure" and "strongly pure". David also 
describes "pure factory functions" (without calling them that) as 
"not [taking] any arguments with mutable indirections". So we got 
that right, too.

But on memoization, David says: "When coming across a pure 
function with immutable parameters, only the identity of the 
arguments has to be checked in order to be able to optimize 
several calls down to one [...]. On the other hand, if an 
argument type contains indirections and is only const, somebody 
else could modify the data between two calls, requiring »deep« 
comparisons that might not be feasible for large data structures 
in the runtime case, or extensive data flow analysis in a 
compiler."

Looks like the spec misses the requirement of having only 
immutable parameters.


[1] https://klickverbot.at/blog/2012/05/purity-in-d/


More information about the Digitalmars-d mailing list