Last active
July 19, 2022 16:41
-
-
Save NostraDavid/8265283219efad2ed26f9061a4e84ba6 to your computer and use it in GitHub Desktop.
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
# 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