Do pure functions solve the "return const" problems?

Bill Baxter dnewsgroup at billbaxter.com
Wed Apr 2 14:10:51 PDT 2008


Steven Schveighoffer wrote:
> "Janice Caron" wrote
>> On 02/04/2008, Yigal Chripun wrote:
>>>  1) since the purpose of pure functions as I understand it is thread-safe
>>>  functions,
>> It isn't. A pure function is a function with no side effects.
>>
>>> than why should we care if they have side affects
>> See above. Knowing that a function f is pure allows the compiler to
>> make optimisations it cannot make with non-pure functions. For
>> example:
>>
>>    x = f() + f();
>>
>> can be optimised to
>>
>>   x = 2 * f();
>>
>> thereby eliminating one entire function call. This makes your code go 
>> faster.
>>
>> Pure functions also happen to be thread-safe, but not all thread-safe
>> functions are pure.
> 
> That was my impression too, but read Bill's post closely.  What he is saying 
> is that pure functions do not need invariant parameters, which means they 
> are subject to thread issues.
> 
> If pure functions are not required to take invariant parameters, then they 
> cannot be guaranteed to be thread safe.

Well I of course am just guessing about what will and will not be 
allowed in a pure function inside a procedural language.  I don't think 
there's ever been such a beast before, so no one can really say for sure.

I guess the question is how much extra checking the compiler will do for 
you.  Currently we think 'pure' will cause the compiler to prevent 
accesses to globals.  If you pass in a const object and only
* access it's local data members in a read-only way, or
* call methods on it declared pure,
then that should be enough to guarantee that the purity of the function 
is not lost.

That would allow 5 copies of the function to be run in parallel or in 
any order, or to change f(c)+f(c) into 2*f(c).  But it would not 
guarantee that the function would do the right thing if there were other 
threads mucking with argument in the background.  However, the failure 
there would not be due to lack of purity on the part of the function. 
You could say it's not the function's fault that memory values are 
changing out from under it.  Or you could say it *is* the function's 
fault for relying on memory values that may change.

--bb



More information about the Digitalmars-d mailing list