Array literals' default type
Denis Koroskin
2korden at gmail.com
Fri Oct 9 17:34:32 PDT 2009
On Sat, 10 Oct 2009 02:28:42 +0400, Andrei Alexandrescu
<SeeWebsiteForEmail at erdani.org> 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;
>> Just fucking shoot me. Or better yet, whoever removed array literals
>> with non-constant elements from the language.
>
> Relax. It's a condition known as literalitis. :o)
>
> Literals only have you write [ a, b, c ] instead of toArray(a, b, c). I
> wouldn't see it a big deal one way or another, but the issue is that the
> former is a one-time decision that pretty much can't be changed, whereas
> toArray can benefit of the hindsight of experience.
>
>
> Andrei
I believe it's okay, but compiler should be able to return static arrays
from a function (I'll call it "array", but feel free to substitute any
other function name):
foreach (i; [a, b, c]) { ---> foreach (i, array(a, b,c )) {
// ... // ...
} }
int[3] x = [a, b, c]; ---> int[3] x = array(a, b, c);
The first example could work with any range returned, but can you
initialize a static array with a range?
Well, some language feature could allow that and translate the latter case
into something like this:
int[3] x = void;
foreach (index, value; array(a, b, c)) {
x[index] = value;
}
But then, what would you do with an array overflow? Disallow it? I.e.,
make it impossible to create a static array and initialize it at the same
time?
If range design is essential in D, perhaps the following could be allowed:
int[] someArray = ...;
someArray[] = someRange(); // initializes an array with elements of a
range. Throws an exception if boundaries don't match
And then,
int[3] x = array(a, b, c);
could be translated into
int[3] x = void;
x[] = array(a, b, c);
(unless array doesn't meet range criteria, of course).
You loose compile-time boundaries checking, but that's the best you can do
if you drop [a, b, c] feature, I'm affraid.
More information about the Digitalmars-d
mailing list