[Python-ideas] Rehabilating reduce (as "fold")

Robert Collins robertc at robertcollins.net
Fri Jul 12 08:24:04 CEST 2013


On 12 July 2013 18:01, Nick Coghlan <ncoghlan at gmail.com> wrote:
> The strange contortions of the "fast sum for lists" discussions got me
> wondering about whether it was possible to rehabilitate reduce with a less
> error-prone API. It was banished to functools in 3.0 because it was so
> frequently used incorrectly, but now its disfavour seems to be causing
> people to propose ridiculous things.
>
> The 2.x reduce is modelled on map and filter: it accepts the combinator as
> the first argument, and then the iterable, and finally an optional initial
> value. The most common error was failing to handle the empty iterable case
> sensibly by leaving out the initial value, so you got a TypeError instead of
> returning a result.
>
> So, what if we instead added a new alternative API based on Haskell's "fold"
> [1] where the initial value is *mandatory*:

+1

>     def fold(op, start, iterable):
>         ...

It would be nice to spell it fold(op, iterable, start), so that a
trivial sed can migrate reduce using code to fold. Or perhaps we could
just fix reduce?

> I'd personally be in favour of the notion of also allowing strings as the
> first argument, so you could instead write:
>
>     data = fold("+=", [], iterables)

This seems like an unusual thing in Python, but I can certainly see
it's convenience.
-Rob

-- 
Robert Collins <rbtcollins at hp.com>
Distinguished Technologist
HP Cloud Services


More information about the Python-ideas mailing list