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

Georg Wrede georg at nospam.org
Thu Apr 3 22:58:18 PDT 2008


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.

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



More information about the Digitalmars-d mailing list