Pure functions in D

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 23 21:34:46 PDT 2008


"Christopher Wright"  wrote
> Bruno Medeiros wrote:
>> Walter Bright wrote:
>>> http://www.reddit.com/r/programming/comments/72r6q/walter_bright_pure_functions_in_d/
>>
>> Interesting.
>>
>>  >Parameters to a pure function can be mutable, but calls cannot be 
>> cached or executed asynchronously if the arguments contain any references 
>> to mutable data.
>>
>> Cool, this amounts the same to the "partial pure"/"contextually pure" 
>> idea Don and I discussed some time ago. Good to see you thought of the 
>> same.
>>
>> A few questions:
>>
>> If a pure function can throw, is it required that it always throws given 
>> the same inputs (and throwing the same Exception?).
>>
>> Will memory allocation be considered pure?
>
> Allocating heap memory affects global state, to whit, the garbage 
> collector's state. I can't see how you can allow memory allocation.
>
> You can call new, though, in a pure function, provided it's placement new 
> or scope.

I think memory allocation is an exception, and possibly the only exception, 
to the global-state rule.  If you don't have memory allocation, string 
operations cannot be pure, you can't return classes, etc.  So that limits 
pure to simple math stuff where you can only return structs or primary types 
(int, double, etc.), which IMO would be a waste of time.  Not a lot of code 
deals with only math, most code never does.

-Steve 





More information about the Digitalmars-d mailing list