Functional Combinators in Python

Let’s rewrite toy implementations of standard functional combinators in Python, for fun.

Map

Built-in:

map(lambda n: n * 2, filter(lambda n: n % 2 == 1, [1,2,3]))

[n * 2 for n in [1,2,3] if n % 2 == 1]

A toy-implementation:

>>> def myMap(fn, ls):
...   return [ fn(x) for x in ls ]
...
>>> myMap(lambda x: x**2, [1,2,3])
[1, 4, 9]

Filter

Built-in:

filter(lambda x : x % 2 == 0, range(1,10))

A toy-implementation:

>>> def myFilter(f, ls):
...     return [ x for x in ls if f(x) ]

Reduce (Fold)

Built-in:

>>> reduce(lambda x, y: x if x >= y else y, [1,2,3,10])
10

A toy implementation:

>>> def myFold(fn, ls, acc=None):
...   for x in ls:
...     acc = fn(acc, x)
...   return acc
...
>>> myFold(lambda acc, x: acc + x, [1, 2, 3], -6)
0

flatMap

Built-in: lol

A toy implementation:

>>> def myFlatMap(fn, nestedList):
...   result = []
...   for innerList in nestedList:
...     for x in innerList:
...       result.append(fn(x))
...   return result

or

>>> def myFlatMap2(fn, nestedList):
...     return [ fn(y) for innerList in nestedList for y in innerList ]