Is this function pure?
Nathan Reed
nathaniel.reed at gmail.com
Tue Sep 18 10:53:57 PDT 2007
Janice Caron wrote:
> Is this function pure?
>
> int probablyNotPure(int x)
> {
> try
> {
> char[] a = new char[x];
> return a.length;
> }
> catch
> {
> return 0;
> }
> }
>
> I must assume not, since it's not deterministic. But which part of it
> wrong? Should "new" be forbidden? Or is "try/catch"? Or both?
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.
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.
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. :)
Thanks,
Nathan Reed
More information about the Digitalmars-d
mailing list