Posts Tagged ‘foldr’

Foldr in Python

2011/06/11

In [1, p.70] Graham Hutton gives a nice example of the power of the function “foldr” in Haskell. The following function bin2int provides a very elegant way to convert a binary number to a decimal number:
bin2int = foldr(\x y -> x + 2 * y) 0

Since I am programming Python now, I asked myself how to do foldr in Python.

The answer is surprisingly simple: just reverse x and y in the lambda expression, as well as the list. For instance, bin2int can be implemented in Python as:


def bin2int(x):
  t = copy.deepcopy(x)
  t.reverse()
  return reduce(lambda y,x: x+2*y, t)

Voila. There we got a foldr in python!

[1] Graham Hutton. Programming in Haskell. Cambridge University Press. 2007.