Is this function pure?

Ingo Oeser ioe-news at rameria.de
Tue Sep 18 11:34:22 PDT 2007


Janice Caron wrote:

> Is this function pure?

Yes.

> int probablyNotPure(int x)
> {
>       try
>       {
>               char[] a = new char[x];
>               return a.length;
>       }
>       catch
>       {
>               return 0;
>       }
> }

A valid optimisation is to assume that x -> a.length, since a.length
is directly derived from x. If you don't use (e.g. reference) the memory
you are allocating, the compiler should be free to optimise the allocation
away. The catch will be dead code, but the function is also valid,
with the catch being dead code, since that would happen with infinite
storage or a GC deleting unreachable reference (like D has :-) ).

> 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?

It can be optimised into a deterministic function without any algorithmic
side effect. So that function actually IS deterministic and thus pure :-)


Best Regards

Ingo Oeser



More information about the Digitalmars-d mailing list