foldr function in Python

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Nov 23 05:54:02 EST 2007


On Fri, 23 Nov 2007 00:50:30 -0800, Ant wrote:

> 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.

Alas and alack, I believe that Guido has a distaste for all but the 
simplest functional idioms, and an irrational belief that anything using 
reduce() must be too complex to bear. reduce() is going away, not just 
from the built-ins but (I believe) from the standard library as well. 

The recommendation is that everybody wanting to reduce a sequence to a 
single item should roll their own instead, using an accumulator and a for 
loop instead. To my mind, getting rid of a standard functional tool like 
reduce in favour of rolling your own is as irrational as getting rid of 
for loops and telling people to roll their own from a while loop.

I hope to be proven wrong.



> 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.

Not quite so trivial to implement as fast as the built-in reduce though. 
A slow pure-Python reduce() would be a good way to disqualify reduce() as 
a serious tool, and condemn it to be used only in toy examples.


> 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.


I believe that foldr() is a standard term in functional programming, and 
no more difficult to learn than other programming terms like zip, 
partition, map, iterator or curry.



-- 
Steven.



More information about the Python-list mailing list