Return complete multi-dimensional array after appending

Paul Backus snarwin at gmail.com
Wed Sep 15 21:02:29 UTC 2021


On Wednesday, 15 September 2021 at 20:32:12 UTC, eXodiquas wrote:
> ```d
> [1,0,3,4,0,5]
> .fold!((a, e) => e != 0 ? a[0] ~ e : a[1] ~ e)(cast(int[][]) 
> [[],[]])
> .flatten
> .writeln
> ```
> This should sort all non 0s into the `a[0]` array and all 0s 
> into the `a[1]` array. But it won't work because the `~` does 
> not return the whole array (which is probably better for most 
> of the cases). So the question, is there a way to do this kind 
> of append, but getting the whole array back as a result in std?

You need to use `~=` instead of `~` to mutate an existing array:

```d
import std;

void main()
{
     [1, 0, 3, 4, 0, 5]
         .fold!((a, e) {
             e != 0 ? (a[0] ~= e) : (a[1] ~= e);
             return a;
         })(cast(int[][]) [[], []])
         .joiner
         .writeln;
}
```

Of course, a more idiomatic solution would be to use 
`std.algorithm.partition`:

```d
import std;

void main()
{
     auto arr = [1, 0, 3, 4, 0, 5];
     arr.partition!(e => e != 0); // in-place
     arr.writeln;
}
```


More information about the Digitalmars-d-learn mailing list