Pure functions in D

Bill Baxter wbaxter at gmail.com
Sat Sep 27 15:28:19 PDT 2008


On Sun, Sep 28, 2008 at 7:12 AM, dsimcha <dsimcha at yahoo.com> wrote:
> == Quote from Michel Fortin (michel.fortin at michelf.com)'s article
>> On 2008-09-27 02:07:59 -0400, Walter Bright <newshound1 at digitalmars.com> said:
>> > Bruno Medeiros wrote:
>> >> 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?).
>> >
>> > Yes.
>> >
>> >> 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.
>> Or you could go in between: allow memory allocation exceptions to be
>> caught, but only when not in a pure function. This way pure functions
>> still always give the same result, or fail and allow non-pure code to
>> handle gracefully the situation (displaying an error message for
>> instance).
>> Making pure functions completely non-recoverable would mean that in a
>> GUI app, for instance, every time you'd call a pure function allocating
>> some memory you'd run the risk of terminating the app, which is not
>> really acceptable.
>> And I think memory allocation is a must, given that without it you
>> can't create, or append to, arrays or strings, and you make pure
>> functions limited to working with pre-existing buffers (which would be
>> then passed by reference, preventing hoisting).
>
> What about stack overflows, etc.?  Calling a pure function can also bring down
> your app if you're out of stack space.  I think it's important to remember that
> any notion of functional purity exists at the level of the language abstraction,
> not at the bare metal level.  Therefore, anything that breaks the language
> abstraction is going to break any concept of functional purity.  Heck, given the
> proper hardware or compiler bugs, even functions that are pure by the strictest
> definitions can have side effects.

But I think a stack overflow is something that doesn't usually occur
in a properly written program, and they are also are not something you
can recover from.  Insufficient memory errors can be and often are
recovered from.   E.g. you try to create a giant image in an image
editing program, if there's not enough memory your image editor
*should* realize the image alloc failed and bail out gracefully
telling you there's not enough memory for that operation.

--bb



More information about the Digitalmars-d mailing list