所以这就是我最终写的内容。基本上,在确保它们都相等之后,我正在收集所有具有相同深度级别的数组并检索它们的维度大小。听起来它工作得很好,唯一的事情是我不确定当 depthLevelArrays 的长度等于 0 时该怎么办?它甚至有意义还是我应该抛出一个异常?
import std.stdio;
import std.traits;
void internal( T )( T[] depthLevelArrays, ref size_t[] shape )
{
if ( depthLevelArrays.length == 0 )
writeln( "what to do here?" );
static if ( isArray!( ForeachType!( T ) ) )
{
ForeachType!( T )[] children;
size_t dimensionSize = depthLevelArrays[0].length;
foreach ( element; depthLevelArrays )
{
if ( element.length != dimensionSize )
throw new Exception( "Shape is not uniform" );
foreach ( child; element )
children ~= child;
}
internal( children, shape );
}
else
{
size_t dimensionSize = depthLevelArrays[0].length;
foreach ( element; depthLevelArrays )
if ( element.length != dimensionSize )
throw new Exception( "Shape is not uniform" );
}
shape ~= dimensionSize;
}
auto getMultidimensionalArrayShape( T )( T array )
{
static assert( isArray!( T ) );
size_t[] shape;
internal( [array], shape );
return shape;
}
void main()
{
immutable auto array1d = [1.0, 2.5, 3.4];
auto shape1 = getMultidimensionalArrayShape( array1d );
writeln( "shape1: ", shape1 ); //< [3]
int[5][2] array2d = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]];
auto shape2 = getMultidimensionalArrayShape( array2d );
writeln( "shape2: ", shape2 ); //< [5][2]
auto shape3 = getMultidimensionalArrayShape(
[[[1, 2], [3, 4], [5, 6], [7, 8]],
[[9, 10], [11, 12], [13, 14], [15, 16]],
[[17, 18], [19, 20], [21, 22], [23, 24]]] );
writeln( "shape3: ", shape3 ); //< [2][4][3]
const int[5][4][3][2] array4d;
auto shape4 = getMultidimensionalArrayShape( array4d );
writeln( "shape4: ", shape4 ); //< [5][4][3][2]
}