Comment #0 by bearophile_hugs — 2014-11-04T11:05:03Z
I suggest to add to Phobos a simple function "arrayShape", that given a nD array performs:
1) calls isRectangular (Issue 13684 ) to verify the input array is complete.
2) Returns a n-tuple of the lengths of matrix sides.
Examples:
arrayShape([1, 2]) => tuple(2)
arrayShape([[1, 2], [3, 4], [5, 6]]) => tuple(3, 2)
arrayShape([[1, 2], [3], [5, 6]]) => exception
This is useful to quickly compare the shape of nD arrays, when you need them to be of the same sizes:
void foo(int[][] a1, float[][] a2)
in {
assert(a1.arrayShape == a2.arrayShape);
} body {}
Comment #1 by bearophile_hugs — 2014-11-05T09:53:56Z
If arrayShape returns a specialized struct instead of a generic tuple, then it's possible to add a method to the struct (otherwise a free function that takes a tuple is acceptable using UFCS), like "allocate", that allows to create an array of given shape:
auto a1 = new int[][](10, 5);
auto s1 = a1.arrayShape;
auto a2 = s1.allocate!double; // 2D matrix of NaNs doubles.
assert(a1.arrayShape == a2.arrayShape);
auto a3 = s1.allocate!double(5.0); // Initialized to 5.0.
assert(a1.arrayShape == a3.arrayShape);
auto a4 = s1.allocate!double((r, c) => r * c); // Initialized to r*c.
assert(a1.arrayShape == a4.arrayShape);
Comment #2 by dlang-bot — 2021-07-25T12:49:07Z
@lucica28 created dlang/phobos pull request #8178 "[DSSv3] Fix issue 13685 - add function arrayShape" fixing this issue:
- Fix issue 13685 - add function arrayShape
https://github.com/dlang/phobos/pull/8178
Comment #3 by razvan.nitu1305 — 2021-07-29T07:27:47Z
Closing as per kinke's comment:
"I don't think Phobos needs such a function; it may encourage people to think jagged arrays (arrays of arrays) are a reasonable way to represent such rectangular multidimensional arrays, while we have a much better suited library for that: http://mir-algorithm.libmir.org/mir_ndslice.html
Using join() for the recursion and thus requiring potentially huge temporary buffers for such a check is bad."