Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Compare compose
def square (x):
return x ** 2
def increment (x):
return x + 1
def half (x):
return x / 2
from functools import reduce
def recursive_compose(*funcs):
def inner(data, funcs=funcs):
return inner(funcs[-1](data), funcs[:-1]) if funcs else data
return inner
def iterative_compose(*functions):
def inner(arg):
for f in reversed(functions):
arg = f(arg)
return arg
return inner
# def _compose2(f, g):
# return lambda *a, **kw: f(g(*a, **kw))
def _compose2(f, g):
return lambda x: f(g(x))
def reduce_compose1(*fs):
return reduce(_compose2, fs)
def reduce_compose2(*funcs):
return lambda x: reduce(lambda acc, f: f(acc), reversed(funcs), x)
import timeit
composes = (recursive_compose, iterative_compose,
reduce_compose1, reduce_compose2)
def manual(x):
return square(increment(half(x)))
fn = lambda: manual(5)
print('manual compose', min(timeit.repeat(fn)), fn())
for compose in composes:
_compose = compose(square, increment, half)
fn = lambda: _compose(5)
result = min(timeit.repeat(fn))
print(compose.__name__, result, fn())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment