Is this function pure?
Lutger
lutger.blijdestijn at gmail.com
Tue Sep 18 07:59:26 PDT 2007
Steven Schveighoffer wrote:
> "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
>
>
That's true, using 'new' does make a function impure. That doesn't mean
it cannot be referentially transparent though.
Even if some 'impure' operations were to be allowed, in the case of new
you would also have to take custom allocators into account.
More information about the Digitalmars-d
mailing list