Thursday, September 30, 2010

Using reduce() to Implement map() and filter()

map() and filter() are by far the most popular of the big three higher-order functions that Python borrowed from functional programming. reduce(), the most convoluted and intricate of the three, has sadly been removed as a built-in in Python 3.0, forcing us to write neater code. Fortunately map() and filter() were both kept, even though list comprehensions are far easier to understand. There is hope for us yet!

map() is a very rigid function -- its behaviour is very easy to predict because it does exactly what it looks like it does. filter(), too, has very limited use and has a single specific purpose (filtering). map()'s usage has no overlap with filter()'s and vice versa.

reduce() is the odd one out -- it's incredibly flexible and fun to use. In fact, reduce() can be used as a replacement for both map() and filter().

def map(f, list):
    return reduce(lambda p, n: p + [f(n)], 
                  [[]] + list)

def filter(f, list):
    return reduce(lambda p, n: p + ([n] if f(n) else []), 
                  [[]] + list)

Off the top of my head I can't think of a way to accomplish either of these tasks without sticking a [] at the start of list. If you have a way, please comment!

1 comment:

  1. You can set the initializer argument of reduce to an empty list, like this

    def mymap (f, xs):
    return reduce(lambda a, x: a + [f(x)], xs, [])

    ReplyDelete