Is this function pure?

Steven Schveighoffer schveiguy at yahoo.com
Tue Sep 18 07:36:51 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?

I would guess that it is not pure, as it is having side effects.  The new 
call is modifying global state (that of the garbage collector), so I don't 
see how that 'new' call can be pure.  From what I understand, a pure 
function can only call other pure functions.

So I think to answer your question, new should be forbidden.

-Steve 





More information about the Digitalmars-d mailing list