How do "pure" member functions work?

Don nospam at nospam.com
Mon Aug 22 13:19:50 PDT 2011


Timon Gehr wrote:
> On 08/21/2011 09:10 PM, Don wrote:
>> bearophile wrote:
>>> Sean Eskapp:
>>>
>>>> Oh, I see, thanks! This isn't documented in the function documentation!
>>>
>>> D purity implementation looks like a simple thing, but it's not
>>> simple, it has several parts that in the last months have be added to
>>> the language and compiler, and we are not done yet, there are few more
>>> things to add (like implicit conversion to immutable of the results of
>>> strongly pure functions). It will need several book pages to document
>>> all such necessary design details.
>>>
>>> Bye,
>>> bearophile
>>
>> It is actually very simple: a function marked as 'pure' is not allowed
>> to explicitly access any static variables.
>> Everything else is just compiler optimisation, and the programmer
>> shouldn't need to worry about it.
> 
> It can be of value to know that a function is pure as in mathematics if 
> it is strongly pure, but can have restricted side-effects if it is 
> weakly pure.

Well, from the compiler's point of view, it's more complicated than 
that. There are const-pure as well as immutable-pure functions. A 
const-pure function has no side-effects, but cannot be optimised as 
strongly as an immutable-pure function.

BTW: The whole "weak pure"/"strong pure" naming was just something I 
came up with, to convince Walter to relax the purity rules. I'd rather 
those names disappeared, they aren't very helpful.

But the basic point is, that knowing that there are no static variables 
is hugely significant for reasoning about code. The strong pure/weak 
pure distinction is not very interesting (you can distinguish them
using only the function signature).


More information about the Digitalmars-d-learn mailing list