Idea: partially pure functions

Bruno Medeiros brunodomedeiros+spam at com.gmail
Thu May 1 07:35:45 PDT 2008


Don wrote:
> 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.
> 

I state that if you have 'pure' implemented (in a sensible manner), it 
takes zero effort to implement partial/contextual pure.

The definition of partial pure functions requires no extra effort from 
the compiler to check. (The *same* check for normal pure functions is 
made: that no external state is accessed unless invariant)

The usage of partial pure functions also requires no extra effort. 
Inside a pure function body, the compiler already has to check if no 
external, non-invariant variables are accessed, like this:

   Foo globalVar;

   pure void func(...) {
     localVar = globalVar + 1; // not allowed

then just apply this same check on *any* expression, including function 
call expressions:

   partiallyPureFunction(localVar, globalVar); // not allowed
   partiallyPureFunction(localVar, localVar2); // but this is allowed


-- 
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