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!
You can set the initializer argument of reduce to an empty list, like this
ReplyDeletedef mymap (f, xs):
return reduce(lambda a, x: a + [f(x)], xs, [])