"fold": a replacement for "reduce"

Simen Kjærås simen.kjaras at gmail.com
Thu Mar 27 08:54:04 PDT 2014


On 2014-03-27 15:33, Meta wrote:
> On Thursday, 27 March 2014 at 13:23:27 UTC, monarch_dodra wrote:
>> "fold" (from what I understood) is what you call "foldl". It was
>> discussed to not introduce "foldr", as it's just
>> "fold!(binaryReverseArgs!Fun)(range.retro);".
>
> Rolls right off the tongue. We seriously need a better alias for
> binaryReverseArgs.

Is it even necessary to specifically have a binary version of that?
This seems to be a working generalization of binaryReverseArgs:

template reverseArgs(alias pred)
{
     import std.typetuple : Reverse;
     auto reverseArgs(Args...)(Args args)
         if (is(typeof(pred(Reverse!args))))
     {
         return pred(Reverse!args);
     }
}

unittest
{
     import std.functional;
     alias gt = reverseArgs!(binaryFun!("a < b"));
     assert(gt(2, 1) && !gt(1, 1));
     int x = 42;
     bool xyz(int a, int b) { return a * x < b / x; }
     auto foo = &xyz;
     foo(4, 5);
     alias zyx = reverseArgs!(foo);
     assert(zyx(5, 4) == foo(4, 5));

     int abc(int a, int b, int c) { return a * b + c; }
     alias cba = reverseArgs!abc;
     assert(abc(91, 17, 32) == cba(32, 17, 91));
}

On the same note, binaryFun and unaryFun seem to me unnecessary 
specializations of a more general 'fun' template. Philippe Sigaud has an 
implementation in his dranges called naryFun 
(https://github.com/PhilippeSigaud/dranges). That code has apparently 
not been touched for at least two years, so YMMV.

--
   Simen


More information about the Digitalmars-d mailing list