"fold": a replacement for "reduce"

Graham Fawcett fawcett at uwindsor.ca
Tue Mar 25 11:02:48 PDT 2014


On Tuesday, 25 March 2014 at 17:22:45 UTC, monarch_dodra wrote:
> I'm working on something called "fold". It is designed as 
> nothing more than a replacement for "reduce", but where the 
> seed comes *second* in terms of arguments. It allows this:
>
> someLongUFCSChain().reduce(intoThis);
>
> It might not look like this, but it is a *constant* source of 
> nuisance. In particular, chains that start out like this:
> someLongUFCSChain().reduce();
> Need to be changed into this to add a seed:
> reduce(someLongUFCSChain(), intoThis);
>
> After a couple of tries to "swap" the arguments, it was 
> observed that it simply couldn't be done wihthout silent 
> run-time breakage. So that was not acceptable.
>
> The solution: Re-introduce "reduce" under a new name: "fold".
> Simple as that.
>
> --------
>
> I'm taking this naming-changing event as an opportunity to 
> "cleanup" reduce too. One thing that gets on my nerves is that 
> "range.reduce()" is not nothrow, because it throws an exception 
> if the range is empty.
>
> I think this is wrong. popping an empty range is an *Error*, 
> and should be validated by the programmer. Because of this, it 
> is currently not possible to use "reduce(range)" in nothrow 
> context.
>
> This however, even with a name change, it *is* change of 
> behavior. Do you feel this is acceptable? Do you want this 
> change at all? Or do you think an Exception is fine?

My knee-jerk observation is that the documentation for 'fold' 
should indicate that it's a left fold, i.e., the sequence of 
operations associates to the left (in other words, it's 
sequence-iterative, not sequence-recursive). It's a small thing, 
but it might help Haskellers and Schemers to orient themselves.

http://srfi.schemers.org/srfi-1/srfi-1.html#fold
http://srfi.schemers.org/srfi-1/srfi-1.html#fold-right

Graham


More information about the Digitalmars-d mailing list