Do pure functions solve the "return const" problems?

Steven Schveighoffer schveiguy at yahoo.com
Wed Apr 2 07:58:00 PDT 2008


"Bill Baxter" wrote
> Russell Lewis wrote:
>> Steven Schveighoffer wrote:
>>> Having never used pure functions, I'm not sure that this is the case for 
>>> C++'s pure functions, but I thought pure functions for D would require 
>>> invariant arguments, no?  Otherwise, how do you guarantee another thread 
>>> doesn't come along and munge the data while the pure function is 
>>> running?
>>
>> Interesting question, I don't really know the answer.  However, it seems 
>> to me that "pure" is a statement that you are making about the function, 
>> not necessarily about the caller.  That is, "pure" means "this function 
>> does not have side-effects, so use it with impunity," whereas "invariant" 
>> means "the caller must obey rules that the function is relying on."
>>
>> Put another way, saying that a function is "pure" allows the caller to 
>> make certain optimizations.  Saying that the arguments are invariant 
>> allows the pure function to optimize internally.
>
> Right.  If it's pure *it* doesn't modify its arguments (or any other data 
> that isn't local to the function).  That enables you to run N copies of 
> that function in parallel without worrying.  Or N copies of any 
> combination of pure functions without worrying.  Keeping other threads 
> from mucking with the data referred to by the pure functions is the user's 
> responsibility.
>
>> I think that it might be quite possible to have a pure function which 
>> doesn't require invariant arguments...it would just lose out on internal 
>> optimization opportunities.
>
> Maybe.  I'm not sure what those extra optimizations would be, though.  I 
> don't believe that code generation usually takes into account the 
> possibility that some other thread might be clobbering your data.  If 
> there is another thread clobbering your data, that's your fault for not 
> mutexing properly.  Invariant may allow you to eliminate a data-protecting 
> mutex, but I'm not sure how that helps the compiler. Maybe synchronized 
> blocks' mutexes could automatically be made no-ops using knowledge of 
> invariant?

Like I said, never used pure functions before.  So what you are saying is 
that the purpose of pure functions is to allow parallelization within the 
context of a SINGLE thread?  So multiprogramming has nothing to do with 
multi-threading?

I always thought Walter's grand vision was to use pure functions to make 
multi-threaded programming easier...

-Steve 





More information about the Digitalmars-d mailing list