Skip to content

Instantly share code, notes, and snippets.

@NostraDavid
Last active July 19, 2022 16:41
Embed
What would you like to do?
# Note that the "# %%" thing is from Jupyter Notebooks, which should be supported by vscode by default :)
# Just run the code with the "run code" button that pops up right above the "# %%"
# %%
import functools
from typing import Callable
ComposableFunction = Callable[[float], float]
def compose(*functions: ComposableFunction) -> ComposableFunction:
return functools.reduce(lambda f, g: lambda x: g(f(x)), functions, lambda x: x)
def add_three(x: float) -> float:
return x + 3
def multiply_by_two(x: float) -> float:
return x * 2
def add_n(x: float, n: float) -> float:
return x + n
# %%
x = 12
x = add_three(x)
x = add_three(x)
x = multiply_by_two(x)
x = multiply_by_two(x)
print(f"Result: {x}")
# %%
my_func = compose(add_three, add_three, multiply_by_two, multiply_by_two)
result = my_func(12)
print(f"Result: {x}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment