D const design rationale

Lutger lutger.blijdestijn at gmail.com
Sat Jun 23 07:09:07 PDT 2007


Reiner Pope wrote:
> You mention functional programming a fair bit with respect to const, 
> which is nice to hear. But nothing in the current const system allows 
> you to declare a verifiably 'pure' function; can we expect some 
> annotation for functions which says 'this function doesn't read/write 
> any global variables?'
> 
>     int b
> 
>     int foo()
>     {
>         b++;
>         return b * 2;
>     }
> 
>     pure int square(int x)
>     {
>         return x * x;
>     }
> 
>     pure int baz()
>     {
>         return foo(); // fails: foo is not pure
>     }

I have two questions which relate to this.

1). Can invariant member functions change globals and / or static 
members? According to the doc I would think so, but the compiler crashes 
with this assert in that case: ito->isInvariant() on line 335 in file 
mtype.c.

If invariant member functions only guarantee invariance on the object / 
struct they are member of, is this the desired semantics? When looked at 
from the pov of an ADT, invariant member functions do not guarantee 
immutability of an object / struct, since their evaluation can rely on 
outside mutable state.

I'm not sure I can oversee the consequences, but what are the obstacles 
to defining the semantics of invariant member functions as pure functions?

2) What are the semantics of invariant free functions, or do they not 
have any special meaning? Again, can invariant be used to mean pure 
here? It would seem logical to me to apply invariance to the evaluation 
of functions as well as what they possibly refer to.



More information about the Digitalmars-d mailing list