pure functions without invariant (a get-rid-of-const proposal)

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Sun Mar 8 09:32:20 PDT 2009


hasen wrote:
> The line of thinking for introducing const/invariant seems to go like this:
> 
> - D needs to be suitable for parallelism
> - let's introduce pure functions
> - pure functions need to accept immutable data only
> - let's introduce const!! (invariant)

That's not the line of reasoning. Invariant data has other uses - it is 
data that can be shared between threads without prejudice. Pure 
functions themselves are ok with any inputs, and put "const" in the 
parameter types to clarify to the caller they won't change the arguments.

> OK, I can agree with most of this, except for the last part! It's not 
> necessary that invariant is needed to introduce pure functions into D. 
> There must be better ways.

This is a non-problem. Invariant is not needed to introduce pure 
functions into D at all.

> First of all, one could argue, why? what's wrong with invariant?
> 
> Well, there are a number of things that are wrong with it:
> 
> First of all, immutable data is a concept, implementing it as 
> "invariant" seems kind of hackish. By definition, immutable data doesn't 
> change. Forcing invariant on top of a mutable type is like saying "This 
> data would usually change, but please, for this instance, make it not 
> un-changeable!"
> This is a HACK.

On the contrary, it's a very principled approach. Const types are proper 
supertypes of their mutable counterparts. Immutable types are proper 
subtypes of const types. It's an established approach. Please google "A 
theory of type qualifiers" by Jeff Foster.

> Immutable types should have immutability be a 
> fundamental part of the type, not some kind of a glue on top of it; a 
> flag that's set on or off!

That is quite what's happening - the flag is kept during compilation though.

> For instance, it doesn't make sense to have an invariant pointer to 
> invariant pointer to invariant data. If the data is invariant, then why 
> access it through pointers at all?

All interesting data has indirection. You couldn't have an immutable 
list without indirection.

> When data is immutable, then all you need is the data! You shouldn't 
> need to know where is it stored.
> 
> Invariant pointers just don't make sense!

Of course they do. You may want to rethink your argument. It rests on 
invalid premises and inevitably can't go interesting places.


Andrei



More information about the Digitalmars-d mailing list