allocTensorShape function
Allocates a nested list structure matching the given tensor shape.
Recursively builds nested lists where the innermost dimension contains doubles initialized to 0.0.
Implementation
Object allocTensorShape(List<int> shape) {
if (shape.isEmpty) return <double>[];
Object build(int depth) {
final int size = shape[depth];
if (depth == shape.length - 1) {
return List<double>.filled(size, 0.0, growable: false);
}
switch (shape.length - depth) {
case 2:
return List<List<double>>.generate(
size,
(_) => build(depth + 1) as List<double>,
growable: false,
);
case 3:
return List<List<List<double>>>.generate(
size,
(_) => build(depth + 1) as List<List<double>>,
growable: false,
);
case 4:
return List<List<List<List<double>>>>.generate(
size,
(_) => build(depth + 1) as List<List<List<double>>>,
growable: false,
);
default:
return List.generate(size, (_) => build(depth + 1), growable: false);
}
}
return build(0);
}