Unofficial wish list status.(Jul 2008)

Steven Schveighoffer schveiguy at yahoo.com
Wed Jul 23 07:53:59 PDT 2008


"Jason House" wrote
> Walter Bright Wrote:
>> The missing ingredient here is what the 'pure' modifier for functions
>> provides. That is the ability to diagnose attempts to alter global state
>> from within a function that is not supposed to do that. Invariant does
>> not imply pure.
>
>
> That's actually a very key part to my whole point.  There is very little 
> difference between pure and invariant functions.  Why do we need a concept 
> for both?  Under the assumption that we're adding const to support 
> functional programming, I don't understand the motivation for this 
> difference.

You are misunderstanding what an 'invariant' member function is.  The 
function itself is not invariant.  It's a function whose 'this' pointer is 
marked as invariant.

Remember that:

class C
{
    invariant void f() {}
}

Is somewhat equivalent to:

class C
{
}

void f(invariant C this) {}

Note that f is not invariant, but 'this' is.

However, for pure functions, pure describes the function, not the data. 
Invariant describes the data.  In fact, a pure member function would have to 
be marked as:

pure invariant void f();

Or else the compiler would complain that you were trying to call a pure 
function with non-invariant data.

As for how useful would an invariant (but not pure) function be?  Consider 
something like:

class C
{
   int x;
   invariant void printTo(stream s) { s.print(x); }
}

Without invariant member functions, you could not have a function like 
printTo for an invariant class instance.  A pure function would not be able 
to print, because the stream argument would also have to be invariant, and 
most likely, stream.print would not be a pure function.

Note that I'm too lazy right now to look up actual stream objects in Phobos 
or Tango and their syntax, so just imagine that what I wrote compiles :)

-Steve 





More information about the Digitalmars-d mailing list