Pure functions in D

Jason House jason.james.house at gmail.com
Sat Sep 27 18:08:23 PDT 2008


Leandro Lucarella wrote:

> Jason House, el 27 de septiembre a las 07:32 me escribiste:
>> Walter Bright Wrote:
>> 
>> > Bruno Medeiros wrote:
>> > 
>> > > Will memory allocation be considered pure?
>> > 
>> > I don't know yet. If memory allocation failure is a non-recoverable
>> > exception, then pure functions can allocate memory.
>> 
>> Pure functions allocating memory is a nice feature to have. A lot of D
>> code wants to allocate memory.  It would certainly allow more return
>> values from pure functions. I don't know what impacts that'd have on the
>> memory model. I've had the impression that parallelizing pure functions
>> could be lockless.
> 
> But I don't see how a function can be pure if allocates, for example:
> 
> pure Image rotate(Image original)
> {
> Image img = new Image(original.size)
> // some rotation logic
> return img;
> }
> 
> If this "pure" function is called with enough memory, it will return
> a copy of the original image, rotated. If there is no enough memory, the
> function will throw (note that the input is exactly the same for both
> calls, but the result is different).
> 
> You can add some try/catch to make it nonthrow, but if you have no memory,
> you can't possibly return the same image as it would be returned when
> memory is available.
> 
> What about stack allocation? I don't even know what's the current
> behaviour. Can you get out of stack? Is an exception raised? The program
> aborted? Anything else?
> 
> 
> This is a really tricky issue indeed, because not being able to allocate
> in a pure function would reduce their utility greatly.
> 
> 


You're missing the subtleties in what Walter said:
        "If memory allocation failure is a non-recoverable exception, 
        then pure functions can allocate memory."

That means that if an out of memory exception occurs, the pure function
(possibly even the whole program) can not catch the out of memory
exception.  Either a pure function will operate normally and predictably,
or it has a non-recoverable error.  This has to be handled differently than
recoverable errors/exceptions which are predictable/repeatable.



More information about the Digitalmars-d mailing list