Skip to content

Instantly share code, notes, and snippets.

@sli
Last active July 1, 2016 00:46
Show Gist options
  • Save sli/3465eb50acb0532d9a83874571de9430 to your computer and use it in GitHub Desktop.
Save sli/3465eb50acb0532d9a83874571de9430 to your computer and use it in GitHub Desktop.
Function composition and chaining in Python.
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