Re: Pure Factory Functions 💔 `inout`
Steven Schveighoffer
schveiguy at gmail.com
Fri Feb 10 18:01:56 UTC 2023
On 2/10/23 9:37 AM, ag0aep6g wrote:
> On Friday, 10 February 2023 at 14:00:20 UTC, Steven Schveighoffer wrote:
>> It can be weakly pure. The docs are wrong.
>>
>> i.e. this works:
>>
>> ```d
>> pure int *foo(const int *p)
>> {
>> return new int(5);
>> }
>>
>> void main()
>> {
>> int x;
>> immutable int * bar = foo(&x);
>> }
>> ```
>
> That function "has no parameters with mutable indirections". So it's
> strongly pure, not weakly pure.
>
> I'd guess that `inout` counts like `const` with regards to weak/strong
> purity. So a `pure` function with `inout` parameters is also strongly pure.
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".
-Steve
More information about the Digitalmars-d
mailing list