Is this function pure?

Lutger lutger.blijdestijn at gmail.com
Tue Sep 18 07:39:44 PDT 2007


Janice Caron wrote:
> On 9/18/07, Lutger <lutger.blijdestijn at gmail.com> wrote:
>> Janice Caron wrote:
>>> Is this function pure?
>> Putting what the compiler can check aside, isn't it the return statement
>> in the catch block what prevents this function from being pure, or
>> referentially transparent?
> 
> I don't think so, since I could easily rewrite it as
> 
> int probablyNotPure(int x)
> {
>     int n;
>     try
>     {
>         char[] a = new char[x];
>         n = a.length;
>     }
>     catch
>     {
>         n = 0;
>     }
>     return n;
> }

What I meant is that the return value is depending on whether new throws 
or not. This is the case in the above function as well as the one in the 
original post, they amount to the same thing.
 From the standpoint of referential transparency I don't think this 
function is really different from:

int surelyNotPure(int x)
{
     int n = rand();
     if (n > 100)
     {
         return x;
     }
     else
     {
         return 0;
     }
}

But if you write it as this I don't see why it would not be pure:

int probablyPure(int x)
{
     int n;
     try
     {
         char[] a = new char[x];
         n = a.length;
     }
     catch
     {
         throw new FooException;
     }
     return n;
}



More information about the Digitalmars-d mailing list