我有任意数量的咖喱函数:
def curry_explicit(function, arity):
if arity == 0:
return function
def get_args(args):
if len(args) == arity:
return function(*args)
def curry(x):
return get_args([*args, x])
return curry
return get_args([])
如何制作一个将柯里化函数和参数作为输入的 uncurry 函数?
需要类似的结果:
f = curry_explicit(max, 3)
g = uncurry_explicit(f, 3)
print(f(3)(6)(9))
print(g(3, 6, 12))
9
12
也许不是最有效的方法并省略错误检查:
def curry_explicit(function, arity):
if arity == 0:
return function
def get_args(args):
if len(args) == arity:
return function(*args)
def curry(x):
return get_args([*args, x])
return curry
return get_args([])
def uncurry_explicit(f):
def uncurry(*args):
nonlocal f
f = f(args[0])
for a in args[1:]:
f = f(a)
return f
return uncurry
f = curry_explicit(max, 3)
g = uncurry_explicit(f)
print(f(3)(6)(9))
print(g(3, 6, 12))
这个解决方案不需要取消柯里化的数量。