Idea: partially pure functions

Steven Schveighoffer schveiguy at yahoo.com
Wed Apr 30 10:41:54 PDT 2008


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

I really like the idea of 'partially pure'.  It basically allows you to 
build functions from modular pieces, which is key to any successful project. 
To have to implement every piece of common functions every time you write 
one seems very error-prone to me.

However, I tend to agree with Don.  What you want is a relaxation of the 
rules, which can easily happen after pure functions are supported.  In fact, 
you don't even need any new keywords or syntax, the compiler just implies 
the partial purity from the parameter/return types.

As for your idea, to be complete, I'd say there are different levels of 
partially pure functions.

level 1: mutable return value, but const/invariant parameters.  These 
functions can be re-ordered, and can be called from pure or unpure 
functions.  The result cannot be memoized.
level 2: mutable parameters.  These functions cannot be re-ordered, but can 
be used inside pure functions.  They cannot be called from non-pure 
functions.  These also cannot be memoized.

There may be more levels, but I think that's at least a start.

An example of a level 1 partially pure function is new.

A level 2 function may need a new keyword, as the contract is different than 
a level 1 or pure function in that it cannot be called from a non-pure 
function.  Level 1 functions are no different contract-wise than fully pure 
functions, just the optimization is different (cannot memoize).

-Steve 





More information about the Digitalmars-d mailing list