Array literals' default type

Christopher Wright dhasenan at gmail.com
Sat Oct 10 06:47:11 PDT 2009


Don wrote:
> Christopher Wright wrote:
>> Don wrote:
>>> I don't understand why runtime-determined array literals even exist.
>>> They're not literals!!!
>>> They cause no end of trouble. IMHO we'd be *much* better off without 
>>> them.
>>
>> You don't see the use. I do. I would go on a murderous rampage if that 
>> feature were removed from the language.
>>
>> For example, one thing I recently wrote involved creating a process 
>> with a large number of arguments. The invocation looked like:
>> exec("description", [procName, arg1, arg2] ~ generatedArgs ~ [arg3, 
>> arg4] ~ moreGeneratedArgs);
>>
>> There were about ten or fifteen lines like that.
>>
>> You'd suggest I rewrite that how?
>> char[][] args;
>> args ~= procName;
>> args ~= arg1;
>> args ~= arg2;
>> args ~= generatedArgs;
>> args ~= arg3;
> 
> Of course not. These runtime 'array literals' are just syntax sugar for 
> a constructor call. Really, they are nothing more.

I'm quite surprised that there is a runtime function for this. I would 
expect codegen to emit something like:

array = __d_newarray(nBytes)
array[0] = exp0
array[1] = exp1
...

> At worst, it would be something like:
> 
> exec("description", createArray(procName, arg1, arg2) ~ generatedArgs ~ 
> createArray(arg3, arg4) ~ moreGeneratedArgs);

PHP does this. I haven't used PHP enough to hate it.

> Depending on what the 'exec' signature is, it could be simpler than 
> that. But that's the absolute worst case.
> 
> The language pays a heavy price for that little bit of syntax sugar.

The price being occasional heap allocation where it's unnecessary? The 
compiler should be able to detect this in many cases and allocate on the 
stack instead. Your createArray() suggestion doesn't have that advantage.

Or parsing difficulties? It's not an insanely difficult thing to parse, 
and people writing parsers for D comprise an extremely small segment of 
your audience.

Or just having another construct to know? Except in PHP, you can't use 
arrays without knowing about the array() function, and in D, you can't 
easily use arrays without knowing about array literals. So it's the same 
mental load.

You could say array() is more self-documenting, but that's only when you 
want someone who has no clue what D is to read your code. I think it's 
reasonable to require people to know what an array literal is.

What is the price?



More information about the Digitalmars-d mailing list