"fold": a replacement for "reduce"

monarch_dodra monarchdodra at gmail.com
Mon Mar 31 08:48:59 PDT 2014


On Monday, 31 March 2014 at 13:05:24 UTC, bearophile wrote:
> OK, thank you. So the price for that "in" is to use a dup :-) 
> (Or use lower level code).
>
> Bye,
> bearophile

I'd think so yes. But given you are calling "array" for every 
iteration, it doesn't look like a ludicrous overhead.

That said, if you were reduce *into* your actual seed (the dup'ed 
array) instead of duplicating it on every iteration, it should be 
better.

I think your code is simplified, but consider this:

//----
uint[] foo3(const(uint[])[] X)
{
     assert(!X.empty);
     auto seed = X.front.dup;
     X.popFront();
     return reduce!((i, j) => i[] |= j[])
                   (seed, X);
}
//----

This gives the same "logical" result, but reuses the seed 
contents on every iteration.

Then, the original dup looks less gratuitous: You are allocating 
your result.


More information about the Digitalmars-d mailing list