How can I implement the uncurry function on python?

81 Views Asked by At

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
2

There are 2 best solutions below

0
Michael Butscher On BEST ANSWER

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.

0
Kelly Bundy On

Variation of Michael's:

from functools import reduce   
from operator import call

def uncurry_explicit(f):
    return lambda *args: reduce(call, args, f)

Attempt This Online!