Created
October 26, 2017 11:42
-
-
Save stephanh42/6c9158c2470832a675fad7658048be9d to your computer and use it in GitHub Desktop.
Attempt at efficient funciton composition on Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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