Skip to content

Instantly share code, notes, and snippets.

@mpkocher
Created March 31, 2014 16:18
Show Gist options
  • Save mpkocher/9896022 to your computer and use it in GitHub Desktop.
Save mpkocher/9896022 to your computer and use it in GitHub Desktop.
compose functions in python
def compose(*funcs):
"""Functional composition
[f, g, h] will be f(g(h(x)))
"""
def compose_two(f, g):
def c(x):
return f(g(x))
return c
return functools.reduce(compose_two, funcs)
@mpkocher
Copy link
Author

Example

In [3]: def f(n: int) -> int: return n + 1                                                                                                                                                                          

In [4]: def g(n: int) -> int: return n * 2                                                                                                                                                                          

In [5]: fg = compose(print, f, g)                                                                                                                                                                                   

In [6]: fg(2)                                                                                                                                                                                                       
5

In [7]: compose(f, g)(2)                                                                                                                                                                                            
Out[7]: 5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment