如何在Python上实现uncurry函数?

问题描述 投票:0回答:1

我有任意数量的咖喱函数:

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
python functional-programming arity curry
1个回答
0
投票

也许不是最有效的方法并省略错误检查:

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))

这个解决方案不需要取消柯里化的数量。

© www.soinside.com 2019 - 2024. All rights reserved.