Skip to content

Instantly share code, notes, and snippets.

@aaron-ortega
Last active November 27, 2021 03:27
Show Gist options
  • Save aaron-ortega/63a2b5fdf5e109458b72b028b8d8069e to your computer and use it in GitHub Desktop.
Save aaron-ortega/63a2b5fdf5e109458b72b028b8d8069e to your computer and use it in GitHub Desktop.
Function Composition in Python
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