Idea: partially pure functions

Steven Schveighoffer schveiguy at yahoo.com
Thu May 1 07:37:55 PDT 2008


"Bruno Medeiros" wrote
> Steven Schveighoffer wrote:
>>
>> 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.
>>
>
> The compiler can only infer partial purity if it has access to the 
> function body (just the same as it can infer normal purity). But if you 
> only have a function signature, you need a keyword.

I meant an *extra* keyword.  If you mark a function as pure, it can be 
partially pure or fully pure depending on the arguments.  However, having an 
extra keyword lets the developer decide whether he is expecting a function 
to be partially pure or not, so there are no surprises :)  I'd vote for a 
new keyword, but this does not need to happen right away.

>
>> 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.
>
> This is already a regular pure function. The idea that a pure function has 
> to return an invariant is a misconception, it can safely return mutable 
> data. It can me memoized just the same (although a copy would have to be 
> made if the result is not invariant)

I would hope that the compiler would not memoize if I returned a mutable 
piece of data, as I would generally expect to use this function as a way to 
initialize some data that I want to build with (in a pure function or 
otherwise).  If I wanted it to memoize, I can return invariant.  For 
example, to memoize on 'new' would be a waste, but 'new' can be considered a 
pure (arguably partially pure) function.  Sometimes memoization is not 
desirable, especially if you are rarely calling the pure function with the 
same arguments.

I guess it all depends on what you consider partially pure :)  I believe the 
current rules as stated on D's website require invariant return data, or 
data that can be implicitly cast to invariant.

-Steve 





More information about the Digitalmars-d mailing list