thoughts on immutability in D

bearophile bearophileHUGS at lycos.com
Thu Sep 22 04:39:00 PDT 2011


Andrei Alexandrescu:

> The initial submission got junked so I resubmitted:
> 
> http://www.reddit.com/r/programming/comments/knn5p/thoughts_on_immutability_in_d/

A logical const can coexist beside the other two (three) kinds of const of D. For simplicity I use the "lconst" keyword.

lconst works similar to the C++ const, and it gives not troubles, because it is orthogonal to the other true consts. You are allowed to safely cast away lconst and then change the variable contents. But if you change it without casting away lconst, the compiler complains statically. Is it better to design lconst too transitive? Maybe lconst is also a "head const" just like C++. This is probably handy enough. So with a lconst array you are allowed to change its contents, but not reassign it or change its length. A lconst doesn't implicitly cast to immutable.

So I think this is well doable. And probably it is useful too. But having four kinds of const in D is a lot of stuff. Maybe it is too much complex.

An alternative solution to face some of the needs of lconst is to define a "trusted pure" that allows to create a pure memoization (a pure memoize).

-----------------------------

Walter:

> You're right. Logical const is only a convention, since it cannot be enforced by the compiler.

Even if it can't be enforced in 100% of the cases, I think it's still useful. So you need to look at the situation from a bit wider point of view.

Bye,
bearophile


More information about the Digitalmars-d mailing list