[:] as empty associative array literal, plus warning for null

bearophile bearophileHUGS at lycos.com
Wed Jul 3 09:55:58 PDT 2013


deadalnix:

> Why not simply [] ? After all, an array is just a very simple 
> type of hashmap, with the identity as hash function.

In a language it's very often handy for different data types to 
have different textual representations and different literals.


If in D code you see:

foo0(null);

That foo0 can be a function that takes a null pointer, and empty 
dynamic array, an empty string, an empty associative array (or 
even a Nullable).


Using [] as empty associative array literal is only a bit better 
than using null:

foo1([]);

Now foo4 can take an empty dynamic array, an empty string, or an 
empty associative array.


Instead if you see:

foo2("");
foo3([]);
foo4([:]);

Now you know what you are giving to that function, it's more 
readable because more explicit.


Currently if you have code like this:

void foo(int[]) {}
void foo(int[int]) {}
void main() {
     foo(null);
}



The compiler gives an error because of the ambiguity:

test.d(4): Error: called with argument types:
     (typeof(null))
matches both:
     temp.d(1): test.foo(int[] _param_0)
and:
     temp.d(2): test.foo(int[int] _param_0)


If you introduce [] as empty associative array literal, the code 
will give similar errors, the situation is not improved much 
compared to null, this is what Kenji was saying.


But if you introduce a literal for associative arrays it's better 
to design it right. [:] avoids the ambiguity, and this code gives 
no errors:

void foo(int[]) {}
void foo(int[int]) {}
void main() {
     foo([]);
     foo([:]);
}


[:] takes just one more char compared to [] so it's doesn't cause 
too much typing (and it's shorter than null). And I think D 
programmers are able to infer what [:] means, I think it's not 
hard to learn.

Bye,
bearophile


More information about the Digitalmars-d mailing list