Skip to content

Instantly share code, notes, and snippets.

@stephanh42
Created October 26, 2017 11:42
Show Gist options
  • Save stephanh42/6c9158c2470832a675fad7658048be9d to your computer and use it in GitHub Desktop.
Save stephanh42/6c9158c2470832a675fad7658048be9d to your computer and use it in GitHub Desktop.
Attempt at efficient funciton composition on Python
from functools import lru_cache
def identity(x):
return x
@lru_cache(None)
def _make_compose(n):
if n == 0:
return lambda: identity
elif n == 1:
return identity
else:
funcnames = ["f{}".format(i) for i in range(n)]
code = "(".join(funcnames) + "(*args, **kws" + (")" * n)
code = "lambda *args, **kws:" + code
code = "lambda " + ", ".join(funcnames) + ":" + code
return eval(code)
def compose(*funcs):
return _make_compose(len(funcs))(*funcs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment