Is this function pure?

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 18 11:18:05 PDT 2007


"Nathan Reed" wrote
> Pure is intended to mimic some of the capabilities of functional 
> languages, yes?  Well, at the implementation level functional languages 
> have to allocate memory just like anyone else, and those allocations can 
> potentially fail just like always.  That doesn't keep functional language 
> functions from being pure, so it shouldn't keep D functions from being 
> pure either.

I tend to agree with you.  But Walter is touting pure functions as being 
able to run simultaneously on two cores.  What happens when both functions 
allocate memory without normal thread locking?  i.e.:

char(invariant)[] x = y() ~ z();  // both y and z are pure

Since y and z are pure, they should be able to run simultaneously on two 
cores.  What happens when they both try to allocate memory?

>
> The function you've written is nondeterministic, but only due to the 
> nondeterminism inherent in memory allocation.  It would be interesting to 
> see if it's possible to write a function that acheives nondeterminism 
> *without* either memory allocation or reading global state (e.g. rand()). 
> I believe it's not.

I don't follow... Isn't this a pure function?  no global state read/memory 
allocation:

int add(int x, int y)
{
   return x + y;
}

Basically, you can do pure functions only on the stack, but the issue 
becomes returning a variable length data structure, such as a string.  I 
think you can't do it unless memory allocation is given a pass.  However, 
then all new operator overrides must be allowed to be pure.

Perhaps you give a single memory allocation routine a free pass, and code 
that deep in the bowels of D, making sure it is thread-safe.  Then all other 
memory allocation routines can declare themselves pure if they use that 
memory allocation routine as a base.

I'm sure Walter has a solution in mind here...

>
> If that is the case, then the only potential source of nondeterminism in 
> pure functions is memory allocation, and I don't think we need to really 
> worry about that too much.  After all, if we've run out of memory, we've 
> likely got bigger problems than our pure functions becoming 
> nondeterministic. :)

I think exception catching should be outlawed in pure functions.  This makes 
the pure function deterministic iff it does not throw an exception.  You can 
handle cases like divide by zero just by checking if the divisor is 0.

-Steve 





More information about the Digitalmars-d mailing list