Is this function pure?

OF nospam at nospammington.com
Tue Sep 18 08:55:07 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?

As long as new char[x] can fail without consistency this function is not pure. That is, the return value depends on something else than x.

However, allocating memory is in itself not necessarily 'unpure', as long as it's predictible (say: I always get memory, else make this computation fail, which could be handled by a caller on a lower and not pure level). 

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). 

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.



More information about the Digitalmars-d mailing list