Array literals REALLY should be immutable

Don nospam at nospam.com
Thu Nov 12 05:28:05 PST 2009


I think this is quite horrible. [1, 2, 3] looks like an array literal, 
but it isn't -- it's an array constructor. It doesn't look like a 
function call. It shouldn't be.

Q1. How do you declare an array literal [1,2,3]?
A. It took me four attempts before I got it.

==========================

int main()
{
    immutable int[] x1 = [1, 2, 3]; // NO - not evaluated at compile time
    static int[] x2 = [1, 2, 3];    // NO - uses thread local storage
    enum int[] x3 = [1, 2, 3];      // NO - not indexable at run time.

    static immutable int[] x4 = [1, 2, 3];  // OK
    static const int[] x5 = [1, 2, 3];      // also OK

    for (int i=0; i< 3; ++i) {
        if (x4[i]==3) return i;
    }
    return 0;
}

(x3 is currently accepted, but that's a bug -- the whole point of 'enum' 
is that you can't take the address of it).

This is really ugly and non-intuitive for something so simple. x1 should 
just work.

Q2: How do you create such an array literal and pass it in a function call?
A. ??? Is this even possible right now?

My code is *full* of these guys. For example, function approximations 
use them (look at any of the special functions code in Tango.math, or 
etc.gamma). Unit tests are full of them. Everyone uses look-up tables.

Bug 2356 is a consequence of this.

By constrast, the stupid array constructors we have now can be 
implemented in a trivial library function:

T[] array(T)(T[] x...) { return x.dup; }

I really don't see how syntax sugar for something so simple can be 
justified, at the expense of basic functionality (lookup tables, 
essentially). Especially when it's creating an inconsistency with string 
literals.




More information about the Digitalmars-d mailing list