pythonfunctional-programmingcurryingarity

How can I implement the uncurry function on python?


I have function curry with arbitrary arity:

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([])

How can I make a uncurry function that will take the curried function and arity as input?

Need a similar result:

f = curry_explicit(max, 3)
g = uncurry_explicit(f, 3)

print(f(3)(6)(9))
print(g(3, 6, 12))
9
12

Solution

  • Maybe not the most efficient way and omitting error checks:

    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):
            result = f
            
            for a in args:
                result = result(a)
            
            return result
            
        return uncurry
        
    f = curry_explicit(max, 3)
    g = uncurry_explicit(f)
    
    print(f(3)(6)(9))
    print(g(3, 6, 12))
    

    This solution doesn't need the arity for uncurrying.