Associative Array Initalizers - Possible Syntax?

Xinok xnknet at gmail.com
Tue Feb 13 22:13:21 PST 2007


 > int tab[char[]] = [["key", 10], ["key2", 11]];

I actually like this syntax. IMO it has one problem though, too much use 
of square brackets [ ] which makes it difficult to read and write if 
initializing a multi-dimensional array.

int arr[char[]][char[]] = [
	["Ten", [["One", 11], ["Two", 12], ["Three", 13]]],
	["Twenty", [["One", 21], ["Two", 22], "Three", 23]]],
	["Thirty", [["One", 31], ["Two", 32], "Three", 33]]]
	];

As you may see, that's very hard to read, and this is only a 2D array. 
Imagine a 3D or 4D array...
Wasn't easy to write either, I had to check my code very carefully to 
make sure I didn't make any mistakes.

To be honest, I think making a unique token is the best solution.

int arr[char[]][char[]] = [
	"Ten" : ["One" : 11, "Two" : 12, "Three" : 13],
	"Twenty" : ["One" : 21, "Two" : 22, "Three" : 23],
	"Thirty" : ["One" : 31, "Two" : 32, "Three" : 33]
	];

This is much easier to read, and definitely easier to write. I didn't 
have to double check my code, and it's just overall quicker.


Just a random idea, please don't ridicule me for this one as I'm sure 
it's a stupid idea anyways, using @ as a token:

int arr[char[]][char[]] = [
	[11 @ "One", 12 @ "Two", 13 @ "Three"] @ "Ten",
	[21 @ "One", 22 @ "Two", 23 @ "Three"] @ "Twenty",
	[31 @ "One", 32 @ "Two", 33 @ "Three"] @ "Thirty",
	];



renoX wrote:
> cracki a écrit :
>> Kirk McDonald Wrote:
>>> I do not find this a compelling reason to require brackets or 
>>> parentheses in all cases. I do like Nicolai's suggestion, though.
>>> (It's very much like Python's syntax, and I believe has been
>>> suggested before.)
>>
>>
>> I agree. Requiring brackets makes not much sense. This is not lisp.
>> We have operator precedence and we can make use of it. And if that
>> fails, use parens. No big deal.
>>
>> I also prefer the "[...]" style to the python/ruby/JSON "{...}"
>> style. It's consistent with nromal array literals and spares the
>> curlies from getting overloaded yet another time.
> 
> Agreed, if ':' conflicts too much with '? :' (and I don't think it does, 
> parenthesis are here to avoid the problem) then let's use '->' or ':>' 
> instead of ':', not a big deal.
> 
> Otherwise don't use any special syntax, after all, an associative array 
> is a just list of key,value pair so
> 
> int tab[char[]] = [["key", 10], ["key2", 11]];
> 
> But I really dislike the idea of separating keys and values, sure 
> sometimes this is terser but it's also much more likely to induce hard 
> to find errors.
> 
> renoX



More information about the Digitalmars-d mailing list