Last active
November 27, 2021 03:27
-
-
Save aaron-ortega/63a2b5fdf5e109458b72b028b8d8069e to your computer and use it in GitHub Desktop.
Function Composition in Python
This file contains 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
import functools | |
from typing import Callable | |
def compose(*functions: Callable) -> Callable: | |
return functools.reduce(lambda f, g: lambda x: g(f(x)), functions) | |
def add_four(x): | |
return x + 4 | |
def multiply_by_three(x): | |
return x * 3 | |
def main(): | |
x = 7 | |
f = compose( | |
add_four, | |
multiply_by_three, | |
multiply_by_three, | |
add_four, | |
) | |
result = f(x) | |
print(f"Result: {result}") # 103 | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment