"fold": a replacement for "reduce"

bearophile bearophileHUGS at lycos.com
Mon Mar 31 03:28:08 PDT 2014


monarch_dodra:

Thank you for the answers.

> I can get it to work for fold though.

Good.


> 2. provide a seed.
> uint[] foo1(uint[][] X)
> {
>     return reduce!((i, j) => zip(i, j)
>         .map!(kw => uint(kw[0] | kw[1]))
>         .array)([uint(0), uint(0)], X);
> }


Unfortunately it doesn't work correctly (because the size of the 
rows is not always 2):



import std.range, std.algorithm, std.array;

// Original correct.
uint[] foo1(uint[][] X) {
     return X.reduce!((i, j) => zip(i, j)
                                .map!(kw => kw[0] | kw[1])
                                .array);
}

// OK
uint[] foo3(in uint[][] X) {
     return reduce!((i, j) => zip(i, j)
                              .map!(kw => kw[0] | kw[1])
                              .array)
                   (X[0].dup, X[1 .. $]);
}

// Modified, not good.
uint[] foo4(uint[][] X) {
     return reduce!((i, j) => zip(i, j)
                              .map!(kw => uint(kw[0] | kw[1]))
                              .array)
                   ([uint(0), uint(0)], X);
}

void main() {
     import std.stdio;
     uint[][] m1 = [[10, 20, 30], [40, 50, 60]];
     foo1(m1).writeln;
     uint[][] m3 = [[10, 20, 30], [40, 50, 60]];
     foo3(m3).writeln;
     uint[][] m4 = [[10, 20, 30], [40, 50, 60]];
     foo4(m4).writeln;
}


Output:

[42, 54, 62]
[42, 54, 62]
[42, 54]

Bye,
bearophile


More information about the Digitalmars-d mailing list