On Saturday, 23 May 2020 at 18:15:32 UTC, Pavel Shkadzko wrote:
I have tried to implement a simple flatten function for
multidimensional arrays with recursive templates but got stuck.
Then I googled a little and stumped into complex
https://rosettacode.org/wiki/Flatten_a_list#D implementation
which requires your arrays to be either TreeList or Algebraic.
That is, it does not work out-of-the-box on something like
int[][][].
I'd like to clarify a couple of questions first.
How come Phobos doesn't have "flatten" function for arrays?
Is there an implementation of flatten that works out-of-the-box
on N-dim arrays outside of Phobos? Excluding "flattened" from
mir.ndslice since it works on Slices.
If the common nd-array isn't jugged (a parallelotop), you can use
fuse function.
----------
/+dub.sdl:
dependency "mir-algorithm" version="~>3.8.12"
+/
import std.stdio: writeln;
import mir.ndslice;
void main() {
auto arr =
[[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9]],
[[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]],
[[20, 21, 22, 23, 24],
[25, 26, 27, 28, 29]]];
auto flatten = arr.fuse.field;
static assert(is(typeof(flatten) == int[]));
assert(flatten == 30.iota);
}
----------
It performs exactly one allocation.