On Friday, 30 January 2015 at 01:08:31 UTC, bearophile wrote:
The D type inference for array literals is now more flexible:

void main() {
    auto[$][$] m1 = [[1, 2], [3, 4], [5, 6]];
    pragma(msg, typeof(m1));  // int[2][3]
    const auto[string] aa1 = ["red": 1, "blue": 2];
    pragma(msg, typeof(aa1)); // const(int)[string]
}


It helps avoid bugs like:

int[5] a = [1,2,4,5];
void main() {}

And it makes the usage of value arrays (fixed size arrays) more handy. We need to minimize the work that the garbage collector has to do. Value arrays help in this. So making value arrays more handy and natural to use is good (regardless how the current Phobos hates them).

- - - - - - - - -

What's missing is a handy and compiler-efficient syntax to create value array literals. Some persons have proposed the "[]s" syntax:


void main() {
    // Some imports here.
    foo([[1, 2]s, [3, 4]]s);
    auto t1 = tuple([1, 2]s, "red");
    auto aa1 = ["key": [1, 2]s];
    auto pairs = 10.iota.map!(i => [i, i + 10]s);
}


To do those same things without the []s syntax you have to write longer code.

----
@nogc
@safe
T[n] s(T = Args[0], size_t n = Args.length, Args...)(auto ref Args args) pure nothrow {
        return [args];
}

@nogc
@safe
T[n] s(T, size_t n)(auto ref T[n] values) pure nothrow {
        return values;
}
        
void main() {
        pragma(msg, typeof(s(1, 2, 3)));
        pragma(msg, typeof([1, 2, 3].s));
}
----

Compilation output:
int[3]
int[3]

You only have to type a dot between the array and the 's'.
Because of pure and nothrow and the low cost of the function call even such a lousy thing like the DMD optimizer should be capable of inlining such a function every time.

Reply via email to