equivariant functions

Robert Fraser fraserofthenight at gmail.com
Thu Oct 16 02:34:13 PDT 2008


Simen Kjaeraas wrote:
> Robert Fraser <fraserofthenight at gmail.com> wrote:
> 
>> In my ideal language, I'd like a const system where instead of the 
>> instances of types (primitive or not) being qualified, the types 
>> themselves were. So a "const class" or "const struct" would mean that 
>> every instance of that type is constant after construction.
>>
>> So you'd have:
>> ---
>> class MutableType
>> {
>>      int x;
>>      this(int _x) { this.x = _x; }
>> }
>> const class ConstType {
>>      int x;
>>      this(int _x) { this.x = _x; }
>> }
>> MutableType m = new MutableType(5);
>> ConstType c = new ConstType(5);
>> m.x = 10; // OK
>> c.x = 10; // ERROR
>> ---
>>
>> All classes that extend a const class would also need to be const. As 
>> for primitives, they would either be manifest-constant or mutable like 
>> in D1. This covers most common use cases very well (except for 
>> constant arrays... hmmmm....) and is easy for the user to understand. 
>> Plus, a "const class" under this system is the same as an "invariant" 
>> under the current system, so no synchronization required. Making 
>> invariant classes (classes that are final and where all members are 
>> final) are a common design pattern in Java.
>>
>> But I'm dreaming here since Walter seems dead-set on this system.
> 
> Like in current d2, you mean?
> 
> const class foo
> {
> }
> 
> class bar : foo
> {
> }
> 
> void main()
> {
>     auto a = new foo();
>     auto b = new bar();
>     foo f = new foo();
>     
>     writefln(typeof(a).stringof);  // prints const(foo)
>     writefln(typeof(b).stringof);  // prints const(bar)
>     writefln(typeof(f).stringof);  // prints const(foo)
> }
> 

Well, yes and no. That is typeof(a) would be just "foo", there would be 
no such thing as a const(foo). Instances of foo just couldn't be changed 
after construction, and the compiler could apply invariant optimizations 
to it as usual. That is, there would be no user-visible const except for 
the ability to declare constant classes/structs.



More information about the Digitalmars-d mailing list