foldr function in Python

MonkeeSage MonkeeSage at
Sat Nov 24 03:56:01 CET 2007

On Nov 23, 7:05 pm, greg <g... at> wrote:

> My feeling is that Python shouldn't provide a bunch of
> different versions of the same function that differ only in
> the degree of currying. If you want a particular curried
> combination, it's easy enough to create it as needed using
> lambda, nested functions or partial().

I agree about noy having different functions with different levels of

What's interesting is that no-one has yet implemented a real foldr on
this thread -- all of the examples have been of foldl. The foldr is
right-associative. This doesn't matter for non-associative functions
like "+", but it does for associative functions like "-".

def foldl(f, l, i): # same as reduce()
  if len(l) == 0:
    return i
    return foldl(f, l[1:], f(i, l[0]))

def foldr(f, l, i):
  def _foldr(f, l, i):
    if len(l) == 0:
      return i
      return _foldr(f, l[1:], f(l[0], i))
  return _foldr(f, l, i)

foldl(int.__sub__, [1,2,3,4], 0)
# -10

foldr(int.__sub__, [1,2,3,4], 0)
# -2


More information about the Python-list mailing list