Skip to content

Instantly share code, notes, and snippets.

@arc279
Created June 23, 2021 09:08
Show Gist options
  • Save arc279/ed1c620f07fef44a06d5dbaec11bcb05 to your computer and use it in GitHub Desktop.
Save arc279/ed1c620f07fef44a06d5dbaec11bcb05 to your computer and use it in GitHub Desktop.
python で関数合成
from functools import reduce
def f_add(x):
def __add(y):
return x + y
return __add
def f_mul(x):
def __mul(y):
return x * y
return __mul
def do(f):
def __do(x):
f(x)
return x
return __do
def f(*funcs):
def __f(initializer):
return reduce(lambda x, f: f(x), funcs, initializer)
return __f
proc = f(
f(
f_add(2),
do(print),
f_mul(2),
do(print),
f_add(3),
do(print),
),
f(
f_add(3),
do(print),
f_mul(2),
do(print),
)
)
print("result: ", proc(4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment