foldr function in Python

Ant antroy at gmail.com
Thu Nov 22 10:02:23 EST 2007


Hi all,

I've just been reading with interest this article:
http://caos.di.uminho.pt/~ulisses/blog/2007/11/20/foldr-the-magic-function/

It's a useful function that (with a more intuitive name) could prove a
compelling addition to the itertools module. In it's python form, it
would be something like this:

def reduce2 (fn, init, seq):
     return reduce(fn, seq, init)

def foldr (function, initial):
    return partial(reduce2, function, initial)

It's a bit different from the other itertools functions, in that
rather than producing an iterator, it produces a function which
reduces a iterator to a singe value.

The advantages I see over reduce are that (a) it provides incentive to
document the code and (b) it promotes reuse. For example:

value = reduce(lambda x, y: "%s%s%s" % (x, "," if x else "", y),
myList, "")

vs.

commaSeparate = foldr(lambda x, y: "%s%s%s" % (x, "," if x else "",
y), "")
commaSeparate(myList)

Of course the lambda function in this case could be a named function,
helping with both readability and reuse, but I think the latter is
conceptually easier to grasp when reading the code.

Discuss.

--
Ant.



More information about the Python-list mailing list