Is this function pure?

Brad Roberts braddr at puremagic.com
Tue Sep 18 09:52:39 PDT 2007


Janice Caron wrote:
> On 9/18/07, OF <nospam at nospammington.com> wrote:
>> Problems arise as long as you allow new to fail like this or if you use the address you get (which of course is not deterministic to the degree we want).
> 
> I think the "address of" operator would have to banned completely from
> pure functions, otherwise you could do
> 
> int definitelyNotPure()
> {
>     int x;
>     return cast(int)&x;
> }
> 
> 
>> Probably it's best to leave memory allocations to implicit allocations in pure functions, but this is tricky if you want to return a new object as a modified version of an input object. I don't know how it's intended for D to solve this nicely, but I'm very interested in hearing it.
> 
> The only way I can think of is the old-fashioned C way, of passing a
> buffer and a length (or in D, an array) into the function, and using
> that and that alone as your memory.
> 
> ...Ooooh, but wait - don't all inputs have to be (transitively) const!?
> 
> Yikes.

Purity typically means that the result of the function is exclusively 
determined by it's inputs.  IE, that the results are entirely 
repeatable.  So, this would be pure:

void foo(in int x, out int y)
{
    y = x+1;
}

No matter how often you call it, for any given value of x, what it sets 
y to is exactly the same.  Obviously, this is a simple example and it's 
essentially isomorphic with the simpler:

int foo(in int x)
{
     return x+1;
}

Whether use of the memory subsystem or other subtle side effects affects 
purity likely becomes a matter of definition.  I personally hope that 
it's included such that your original example is pure.

Later,
Brad



More information about the Digitalmars-d mailing list