Created
August 7, 2012 16:37
-
-
Save rossdylan/3287138 to your computer and use it in GitHub Desktop.
Function composition 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
from functools import partial | |
def _composed(f, g, *args, **kwargs): | |
return f(g(*args, **kwargs)) | |
def compose(*a): | |
try: | |
return partial(_composed, a[0], compose(*a[1:])) | |
except: | |
return a[0] |
Relevant: https://mathieularose.com/function-composition-in-python/
A comment from Fred Loney, gives an elegant solution:
def compose(*funcs):
return lambda x: reduce(lambda v, f: f(v), reversed(funcs), x)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a very old, but still relevant (despite the additions to stdlib in later times, like
partial
) functional.py module (I can't find it's homepage, maybe it expired, its still in cheeseshop though) which I use. It's compose function looks like this:One can define
multicompose
in terms of fold and compose: