Return complete multi-dimensional array after appending

eXodiquas exodiquas at gmail.com
Wed Sep 15 20:32:12 UTC 2021


Howdy everyone. :)

Today I came across a small problem (I mean, I could solve it by 
writing a function that solves my problem, but maybe there is 
something in std that can help me here). Let's say we have the 
following code:

```d
void main() {
   int[][] a = [[],[]];
   (a[0] ~ 5).writeln; // => [5]
}
```

it's quite obvious that `[5]` is printed. Because I am a fan of 
one-liners (we do small code challenges, and I want to show 
what's possible with fold) and ridiculous stuff I tried to do 
something like this:

```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?
And another question, is there a way to tell `fold` about the 
initial value of an empty list without having to cast a `void[]` 
into the list of the desired type?

Thanks in advance. :)

eXodiquas


More information about the Digitalmars-d-learn mailing list