"fold": a replacement for "reduce"

monarch_dodra monarchdodra at gmail.com
Mon Mar 31 01:32:51 PDT 2014


On Sunday, 30 March 2014 at 21:53:16 UTC, bearophile wrote:
> monarch_dodra:
>
>> I'm taking this naming-changing event as an opportunity to 
>> "cleanup" reduce too.
>
> This seems OK, but can fold offer a better solution?:
>
> Bye,
> bearophile

AFAIK, no: Your range's element type (E) is `const(uint)[]`, and 
given your predicate (let's just call it "pred"), `pred(e, e)` 
produces a `const(uint)[]`. There's not much that reduce or 
fold(l) could do about it at that point.

You'd have two (IMO cleaner) solutions.
1. tweak pred to return the right type (*):
uint[] foo1(uint[][] X)
{
     return X.reduce!((i, j) => zip(i, j)
         .map!(kw => uint(kw[0] | kw[1]))
         .array);
}
(*) This currently fails catastrophically with both single and 
multiple pred versions of reduce, due to suboptimal code.

I can get it to work for fold though.

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);
}

In any case, thanks for reporting. I'll make certain this works.


More information about the Digitalmars-d mailing list