const?? When and why? This is ugly!

BCS ao at pathlink.com
Mon Mar 2 12:04:10 PST 2009


Reply to hasen,

> "Transitive const is key to bringing D into this paradigm."
> 
> Really? have you considered other possibilities?
> 
> How about, adding a new attribute to functions: `pure`
> 
> pure real sin( real x ) { ... }
> 
> and design the rest around this concept.

A lot of the current const system IS designed around plans to add pure functions. 
You can almost read immutable as "valid as an arg for a pure function call."

> 
> The compiler must make sure that this function is really pure:
> - native types must be passed by value, not by reference
> - doesn't accept pointers
> - <insert some condition for objects and arrays>
> If these requirements aren't met, the compiler will spit some error
> message "in function <F>: doing <X> voilates the `pure` attribute"
> 

Um... that would be even more restrictive than const. Outside pointers const 
is more or less irrelevant with regards to function arguments so you might 
as well have said "pure functions can't take anything that is const or CAN 
be const"

> objects and arrays will need some special treatment or requirements in
> order to be passed to pure functions.

Const is a lot of very smart peoples best effort to do that special treatment.


> (*) A quick idea might be:
> - For arrays, any statement of the type `a[b] = c` will be illegal
> inside a pure function. and pure functions can only call pure
> functions.

pure int fn()
{
    int[5] foo;
    foo[0] = 5;  /// why ban this
    return foo[0];
}

> However, the advantage is not complicating the type system more than
> is needed.
> 
> Also, what's the deal with const pointers?? Why should `pure` function
> be able to use pointers at all? Is there any real-life use case where
> a pure function needs to access memory instead of some abstract
> concept like a variable/array/tuple?

Say I have several pre computed multi-MB tables that need to be used by a 
function. The tables never change. The function is still pure but I really 
can't pass the table on the stack. The same thing to a lesser degree happens 
with any reference type that is much larger than a pointer.





More information about the Digitalmars-d mailing list