Closed kasparthommen closed 1 year ago
Goods news! Manifold's existing index operator supports multidimensional indexing. The rationale for this approach was discussed in this slack thread: https://app.slack.com/client/T01385BBDLH/C04GTP7V4V9/thread/C04GTP7V4V9-1672214259.219969. The gist of the discussion follows.
Java's array syntax is the "jagged" kind as opposed to the requested "rectangular" kind. Consequently, there is no rectangular index operator to overload, Java's grammar doesn't support that. But this turned out to be a blessing in disguise. Turns out manifold already supports multidimensional indexing.
What I hadn't realized until recently was that the single index operator can be overloaded in each of the dimensions of a multidimensionally indexed type. Essentially, dimensions above the first (D2, D3, etc.) must be explicitly typed and each of those types must overload the index operator accordingly. The outermost (D1) indexed type implements the operator method get(i) where the return type is D2. Likewise, D2 implements get(i) where return type is D3 and so on until the final value reflects the leaf type where both get(i) and set(i, value) are implemented.
Consider a simple, two-dimensional Matrix object.
public class Matrix<T> {
private final Object[][] matrix;
public Matrix(int x, int y) {
this.matrix = new Object[x][y];
}
public D2 get(int i) { return new D2(i); }
private class D2 {
private final int index;
private D2(int index) {
this.index = index;
}
public T get(int i) { return (T) matrix[index][i]; }
public T set(int i, T value) { return (T) (matrix[index][i] = value); }
}
}
With the intermediate D2 class implemented Matrix supports multidimensional indexing.
Matrix<String> matrix = new Matrix(10, 5);
matrix[3][4] = "hi";
String value = matrix[3][4];
System.out.println(value);
It's worth noting Java's existing jagged syntax is generally more appropriate for general multidimensional indexing since the rectangular syntax implies uniform size, which is not always the case. Additionally, in keeping with the principal of least surprise, utilizing Java's existing index operator is probably the more suitable of the two choices.
Remaining IntelliJ issues are fixed. Multiple dimensions via index operator are fully supported.
It would be great if the current indexing operator,
[]
, could also be overloaded used for multi-dimensional access, i.e., as follows:a[i, j, k]
a.get(i, j, k)
a[i, j, k] = c
a.set(i, j, k, c)
Would that be possible? Obviously, an arbitrary number of indexes should be supported, not just 3 like in my example above.