foldr function in Python

Ant antroy at gmail.com
Fri Nov 23 03:50:30 EST 2007


On Nov 22, 7:14 pm, oj <ojee... at gmail.com> wrote:
> On Nov 22, 3:02 pm, Ant <ant... at gmail.com> wrote:
...
> It's basically just one line to implement:
>
> foldr = lambda f, i: lambda s: reduce(f, s, i)
>
> It's just reduce with currying, I'm not sure it adds that much to what
> python already offers.

Yes it's easy to implement. I did it in two steps because I think it's
easier to read. That's not the point I'm trying to make though. sum,
any and all are trivial to implement, yet they made it into the
builtin methods.

The point of those functions I believe to be to promote easier to
understand idioms. Without them people will continue to write ad hoc
reduce based versions (which are less readable and less efficient).
With sum, any and all in the standard library, it becomes easier to
write readable code, and so people will be more likely to do so.

The other benefit is to promote ways of thinking about code that you
may not have come across or thought about before. This is a common
situation when learning new languages - before learning python I would
never have thought to use map or reduce functions, and these are
trivially easy to implement.

So my point really is that foldr (perhaps renamed to make_reducer or
something) could create idioms that are more readable than using
reduce directly.



More information about the Python-list mailing list