Partially pure (Re: Fully transitive const is not necessary)

Don Clugston dac at nospam.com.au
Fri Apr 4 00:52:54 PDT 2008


Georg Wrede wrote:
> Walter Bright wrote:
>> Don Clugston wrote:
>>> Walter Bright wrote:
>>>
>>>> A function is pure or it isn't, there really isn't any room for 
>>>> "unstable" purity, or the point of purity is lost.
>>>
>>> I think there is. A function which accesses a global is inherently 
>>> impure. But, a function which takes a non-invariant argument, can in 
>>> theory safely be called from inside a pure function, provided any 
>>> non-invariant arguments are local variables, or invariant.
>>>
>>> eg.
>>>
>>> class C
>>> {
>>>   int numcalls;
>>>   this() { numcalls=0; }
>>>   void foo() { ++numcalls; } // Not pure - but no global side effects.
>>> }
>>>
>>> pure int bar(int x)
>>> {
>>>     C c = new C;
>>>     for (int i=0; i<x; ++i) c.foo();
>>>     return c.numcalls;
>>> }
>>>
>>> Is bar() pure or not?
>>
>> I think it is pure, although it might be difficult for the compiler to 
>> detect it. Like for CTFE, I think the compiler should start out rather 
>> restrictive about what it regards as pure, and over time expand it as 
>> it gets more capable.
> 
> No.
> 
> The result of having run the function changes something outside the 
> function, and that makes it impure.

foo() is definitely not pure. But bar() doesn't change anything outside bar().

* foo() doesn't read or write anything other than its parameters.
* The only parameters bar() provides to foo() are local.

> It does not matter that what's being changed is hidde behind the bushes 
> in a small tin box.

I don't think that's what happening here. A 'partially pure' function like foo() 
can be wrapped in a pure function.
The question is whether the compiler can allow this, without foo() being marked 
in some way.
It works for CTFE, because in CTFE, the compiler has access to the source code; 
but that's not necessarily true for run time functions.

This partial impurity is not transitive! (whereas accessing a global is transitive).



More information about the Digitalmars-d mailing list