Automatic Inference for Both Key and Value Types of an Associative Array

Meta via Digitalmars-d digitalmars-d at puremagic.com
Thu Aug 7 09:07:37 PDT 2014


Something H.S. Teoh in a recent pull request in Github got me 
thinking that it would be useful in some cases to tell the 
compiler that you want to automatically infer the either the key 
type or value type of an AA. Something like the following:

//typeof(aa) -> string[int]
string[auto] aa = [1:"first", 2:"second"];

//typeof(aa) -> char[int[]]
auto[int[]] aa = [[1]:'a', [2]:'b'];


Of course, if you want to have both inferred, just use plain 
'auto'. This is similar to Kenji's recent compiler changes to 
accept things like:

     // dynamic array type
     immutable[] a4 = [1,2];    // immutable(int)[]
     shared[]    a5 = [3,4,5];  // shared(int)[]
     // partially specified part is unqualified.

     // pointer type
     auto*  p1 = new int(3);  // int*
     const* p2 = new int(3);  // const(int)*


I think the 'immutable[]'/'const[]' type expressions could work 
similarly for AAs, since they are storage classes just like 
'auto'. As per my first example:

//typeof(aa) -> string[immutable(int)]
string[immutable] aa = [1:"first", 2:"second"];

//typeof(aa) -> immutable(char)[int[]]
immutable[int[]] aa = [[1]:'a', [2]:'b'];


A downside is that combining the two *could* lead to some type 
expressions that are very weird looking:

//typeof(aa) -> const(int)[][immutable(char)]
const[][immutable] aa = ['a':[1], 'b':[2]];

//typeof(aa) -> const(const(int)[const(int)])
const(const[const]) aa = [1:1, 2:2];

//WTF???
inout immutable[$][][const[$]][] aa;


Is this a good idea? I don't have the skill to implement it 
currently, but I wanted to throw it out there for comments and 
see what people think.


More information about the Digitalmars-d mailing list