Last active
August 15, 2016 15:44
-
-
Save adammartinez271828/be1cad1cc98f5a62c73b3e5c540d73e1 to your computer and use it in GitHub Desktop.
Compose functions functionally.
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 reduce | |
def compose(*functions, forward=False): | |
"""Compose many (single-argument) functions into a single function | |
Evalutates the fuctions last-to-first by default. Use functools.partial | |
with this for multiargument functions. | |
Also, it is magic. Don't play with it or you'll let the magic out. | |
"Some things you just... maybe shouldn't be allowed to do in a programming | |
language. The human brain is too stupid to utilize computers properly, it | |
seems." | |
Args: | |
*functions (function, function, ...): an arbitrary number of functions | |
forward (boolean): evaluate the functions first-to-last | |
Returns: | |
The composition of *functions, i.e. | |
compose(f, g, h)(x) = f(g(h(x))) | |
Examples: | |
>>> f, g = lambda x: x*2, lambda x: x+2 | |
>>> assert f(g(2)))) == compose(f, g)(2) | |
>>> assert g(f(2)))) == compose(f, g, forward=True)(2) | |
""" | |
if forward: | |
return lambda x: reduce(lambda v, f: f(v), functions, x) | |
else: | |
return lambda x: reduce(lambda v, f: f(v), reversed(functions), x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment