"fold": a replacement for "reduce"

monarch_dodra monarchdodra at gmail.com
Mon Mar 31 05:47:59 PDT 2014


On Monday, 31 March 2014 at 10:28:10 UTC, bearophile wrote:
> monarch_dodra:
>
> Thank you for the answers.
>
>> I can get it to work for fold though.
>
> Good.

I've reconsidered my answer. It is *impossible* to get what you 
are asking for to work, without explicitly passing a seed.

This is because the seed is *initialized* to the range's front. 
Anything other than "const(uint)[]" would simply break the type 
system: If your range only has 1 element, then you'd be returning 
a mutable reference to const data.

So my vote goes to this solution.

//----
uint[] foo3(in uint[][] X)
{
     assert(!X.empty)
     auto seed = X.front.dup;
     X.popFront();
     return reduce!((i, j) => zip(i, j)
                              .map!(kw => kw[0] | kw[1])
                              .array)
                   (seed, X);
}
//----

I re-wrote it that way: It's a bit longer, but a bit more generic 
in terms of customizing your seed.


More information about the Digitalmars-d mailing list