March 4th 2008 Functional Programming in Python

I’ve been experimenting with some functional programming in Python. I haven’t done anything fancy yet, but below is a recursive implementation of the Haskell function foldl in Python. I could’ve written it iteratively, but by writing it recursively, I avoided the need to store any data in variables, thus making it more “purely functional”.

#!/usr/bin/env python

def mult(x,y):
    return x * y

def foldl(f, x, ls):
    if len(ls) == 1:
        return f(x, ls[0])
    else:
        return foldl(f, f(x, ls[0]), ls[1:])

print foldl(mult, 1, [11, 12, 13, 14, 15, 16, 17, 18, 19, 20])

It’s nothing amazing, but I was quite pleased with my efforts.