Last active
July 1, 2016 00:46
-
-
Save sli/3465eb50acb0532d9a83874571de9430 to your computer and use it in GitHub Desktop.
Function composition and chaining in 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
def chain(*args): | |
result = args[0] | |
for func in args[1:]: | |
result = func(result) | |
return result | |
def compose(*funcs): | |
cfuncs = [] | |
for func in funcs: | |
if hasattr(func, '__call__'): | |
cfuncs.append(func) | |
def composed(*args): | |
result = tuple([chain(a, *cfuncs) for a in args]) | |
if len(result) == 1: | |
return result[0] | |
return result | |
return composed | |
if __name__ == '__main__': | |
def add1(x): | |
return x + 1 | |
def times10(x): | |
return x * 10 | |
ch = chain(1, add1, times10) | |
print(ch) | |
co = compose(add1, times10) | |
print(co(1)) | |
print(co(1, 2)) | |
assert(ch == co(1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment