Proposal: Make [][x] and [][a..b] illegal (reserve for multidimensional arrays)

Don Clugston dac at nospam.com.au
Wed Nov 21 05:33:54 PST 2007


 > Bill Baxter wrote:
 >>> 2) D lacks a clean syntax for slices of multiple dimensions.  opSlice
 >>> calls must have one and only one ".."
 >>
 >> Can you propose a syntax for that?

How about making [] more than just a shorthand for [0..$], but rather mean 
"take everything from this dimension and move on".
This would, I think, make it more consistent with its usage in declarations, 
where it is a dimension marker, not a slice.

This would leave the way open for multidimensional array slicing.
For example, access of 5 dimensions would be of the form
auto c = m[][4][][][7];

where [] = take the whole contents of that dimension, or [x] takes only element 
x of it. Just as now, there is an implicit [][][] at the end for any unspecified 
dimensions.

A slice can be inserted in the expression before any dimension is completed; it 
takes a slice of that dimension.
So, for example, with a 2-D matrix m,
auto c = m[4..5][][1];

would mean [ m[4][1], m[5][1] ].
and m[1][4..5] == m[1][4..5][];

would continue to mean [ m[1][4], m[1][5] ].

You can do this right now for user-defined types, but built-in types work 
differently because of a (IMHO) useless redundancy.

     int f[][2] = [[1,2], [3,4], [5,6], [7,8]];
     int [] e = f[][1];
     int [] g = f[1][];
     int [] h = f[1];
     int [] p = f[][][][][][][1][][][][][][][][][][][][]; // isn't this silly???

Currently this is legal. All those expressions are synonyms.
e[0] == g[0] == h[0] == p[0] == f[1][0] == 3.
In my proposal e would mean:
f[0][1], f[1][1], f[2][1], f[3][1]
which would become illegal since it is a strided slice (currently unsupported in 
the language)
and g would be:
f[1][0], f[1][1]
which is the same as h.
In fact, right now, in an expression, any slicing or indexing operation on a 
built-in array after a [] would become illegal.

This would only break existing code which contained (IMHO) bad style and 
confusing redundancy.
If for some reason the existing behaviour was desired (such as in 
metaprogramming or code generation ?), simply change [] to [0..$].
But [] would continue to provide syntactic sugar in the places it was originally 
intended.



More information about the Digitalmars-d mailing list