Pure functions in D

Bruno Medeiros brunodomedeiros+spam at com.gmail
Tue Sep 23 15:19:15 PDT 2008


Steven Schveighoffer wrote:
> Another possibility is that pure functions that accept mutable parameters 
> can only be called from other pure functions, therefore you are guaranteed 
> that the data is not being used in any other thread.
> 

I'm almost certain this is the intended behavior, with the addition that 
you can also call that same pure function from an unpure one, only then, 
the compiler will treat the function as being unpure. This is the gist 
of the "partially pure"/"contextually pure" idea: a function is 
considered pure or not dependent on the immutability of the arguments 
with which it's called. This consideration "happens" on every call. 
Since the optimizations to pure functions are made on the call, and not 
on the body of the function, this is perfectly ok.
I don't see any other behavior that isn't either broken, or more limited 
in functionality.

Also note that in the case where the given (contextually) pure "foo" 
function is called from a pure function, the fact that foo is called 
from a pure function only guarantees that the arguments are not changed 
by anyone else when foo executes, but foo must still be treated as 
unpure. Example:

pure void foo(int* iptr) {
   (*iptr)++; // side effect
}


pure int func() {
   int a = 1;
   foo(&a); // side-effect, cannot optimize this call
   foo(&a); // side-effect, cannot optimize this call
   return a;
}
// Yet func is allways pure.


-- 
Bruno Medeiros - Software Developer, MSc. in CS/E graduate
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D



More information about the Digitalmars-d mailing list