Logical const

Jesse Phillips jessekphillips+D at gmail.com
Tue Nov 30 19:52:01 PST 2010


Fawzi Mohamed Wrote:

> 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.

Don't know what you mean by this.

> 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.

This code is valid, the requirements placed on cast will not allow it to move the data. Even types declared to be immutable my be modifiable when cast to Unqual!(T), but the compiler can not guarantee these.

If I am wrong, please let me know why.

> 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.

Yes, and I don't think compiler support adds any more guarantee than casting those you want to modify in a const function. This Mutable struct is supposed to help verify only modifiable data is cast:

https://gist.github.com/721066

I've taken many example use-cases for logical const and added them as unittests. I think it is fairly reasonable if I could just get an answer to my question about concurrency and declaring immutable types.
 
> 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).

Could you give an example of how lazy evaluation is achieved by modifying state?



More information about the Digitalmars-d mailing list