Idea: partially pure functions

Don nospam at nospam.com.au
Wed Apr 30 07:55:58 PDT 2008


Bruno Medeiros wrote:
> Don wrote:
>> Bruno Medeiros wrote:
>>> I want to conceptualize an idea that has been briefly mentioned in 
>>> the previous pure discussions (by Don I think?), but has not been 
>>> explicitly brought into attention.
>>>
>>> As we know, the current definition of pure functions (according to 
>>> http://www.digitalmars.com/d/2.0/accu-functional.pdf) is that they 
>>> can only access invariant, or local mutable data. This means that all 
>>> of the function's parameters have to be invariant.
>>>
>>> The idea is: let's also allow pure functions to have (and access) 
>>> non-invariant parameters. These won't be normal pure functions, but 
>>> instead "partially" pure functions. Their semantics are: the function 
>>> promises not to change any external/global data, except for the 
>>> parameters that are not invariant. Example:
>>
>> The first case to consider is nested functions.
>>
> 
> Nested functions are a more complicated case than regular functions, as 
> they have other "inputs" other than the parameters: the outer variables.
> So I think that if you implement partial pure semantics for nested 
> functions, then you have it working for normal functions as well.

I don't think so, in practice. Nested functions are a lot easier to 
implement, since while compiling the outer function, the compiler always 
has access to the complete code of the inner function and can confirm 
that the outer function remains pure. It's impossible to change the 
nested function in a way that accidentally violates purity of the outer 
function -- it just won't compile.

But a regular function could appear in a completely different library, 
so the contextually purity needs to be enforced, and this would need a 
language change.

> 
>>
>> But Walter's already said that pure functions will start out very 
>> restricted, and the rules will be relaxed over time. So it's not 
>> really worth worrying about the rules right now.
> 
> True, if we're thinking about compiler implementation only. But in terms 
> of design, this might not be just an improvement, it could a crucial 
> functionality. For example, consider this other example: Suppose you 
> have a pure function with a local object and you want to mutate that 
> object using a mutable method. If you are not able to call the mutable 
> method in the pure function, you might not even be able to describe the 
> method changes inside the pure function, because of Object encapsulation 
> (example: changing a private member).
> 
> So partial pure semantics might be necessary if one wants pure functions 
> to be able to work with objects in the general sense.

Yes, I don't see how objects can be used in pure functions without some 
form of 'contextually pure' functions.




More information about the Digitalmars-d mailing list