Logical const

Fawzi Mohamed fawzi at gmx.ch
Tue Nov 30 16:24:38 PST 2010


On 30-nov-10, at 16:39, Andrei Alexandrescu wrote:

> On 11/30/10 5:25 AM, Max Samukha wrote:
>> On 11/30/2010 02:35 AM, Walter Bright wrote:
>>> Fawzi Mohamed wrote:
>>>> logical const is useful for lazy functions and memoization, and if
>>>> implemented correctly it is perfectly safe.
>>>> As I said in an older discussions, to have it with the current  
>>>> system
>>>> all that is needed is some guarantees that the compiler will not
>>>> disallow "unsafe" changes (by moving to read only memory for
>>>> example)in some cases.
>>>> For example casted mutable types, so that casting to mutable works.
>>>
>>> D allows escape from the type system, but the programmer who does  
>>> that
>>> loses the guarantees, and it's up to him to ensure that the result  
>>> works.
>>>
>>> String literals, for example, are going to often wind up in read  
>>> only
>>> memory.
>>
>> The problem is that logical const has many perfectly valid use cases.
>> You cannot simply tell people: "Don't use it. It is a fraud". They  
>> will
>> still be using casts or not using D. As casting away const is  
>> undefined
>> behavior in D, the outcome will be every second non-trivial D program
>> relying on undefined behavior.
>
> I'm not seeing half of non-trivial C++ programs using mutable.

The thing is that a lazy structure is very useful in functional  
programming.
A lazy evaluation is something that should be possible using pure and  
immutable.
I find it jarring that to do that one has to avoid D pure and immutable.

To be able to safely use pure and immutable as I said one would need  
some idioms that are guaranteed to be non optimized by the compiler.
for example casting a heap allocated type should be guaranteed to  
remain modifiable behind the back:
auto t=new T;
auto t2=cast(immutable(typeof(t)))t;

auto tModif=cast(typeof(t))t2; // the compiler has not moved or  
flagged the memory of t, so one can modify tModif.

clearly this is unsafe and it is up to the implementer to make sure  
that the object is really logically const
and no function will see the internal changes.

This is something that should be done sparingly, probably just in  
library code implementing lazy evaluation or memoization (but code  
that might be mixed in).


More information about the Digitalmars-d mailing list