Currying decorator in python

前端 未结 9 1793
故里飘歌
故里飘歌 2020-12-03 03:11

I am trying to write a currying decorator in python, and I think I\'ve got the general idea down, but still got some cases that aren\'t working right...

def          


        
9条回答
  •  北海茫月
    2020-12-03 03:48

    Here is my version of curry that doesn't use partial, and makes all the functions accept exactly one parameter:

    def curry(func):
    """Truly curry a function of any number of parameters
    returns a function with exactly one parameter
    When this new function is called, it will usually create
    and return another function that accepts an additional parameter,
    unless the original function actually obtained all it needed
    at which point it just calls the function and returns its result
    """ 
    def curried(*args):
        """
        either calls a function with all its arguments,
        or returns another functiont that obtains another argument
        """
        if len(args) == func.__code__.co_argcount:
            ans = func(*args)
            return ans
        else:
            return lambda x: curried(*(args+(x,)))
    
    return curried
    

提交回复
热议问题