Skip to content

Instantly share code, notes, and snippets.

@ecamellini
Last active March 30, 2018 08:01
Show Gist options
  • Save ecamellini/500124ccb0dad7a9955e8471539d7b3e to your computer and use it in GitHub Desktop.
Save ecamellini/500124ccb0dad7a9955e8471539d7b3e to your computer and use it in GitHub Desktop.
Currying example in python

Currying

See the Definition.

Implement the function add so that it works in the following way:

add(1,2)  # 3
add(1)(2) # 3

Solution:

def add(*args):
    if len(args) == 2:
        return sum(args)
    elif len(args) == 1:
        return lambda x: x + args[0]
    else:
        raise ValueError("at least 1 argument needed.")

Make the second version (i.e, add(1)(2)) work for an indefinite number of arguments.

Solution: this can be achieved by using a closure. Note: this works only in python 3 and it is not actually real currying in terms of syntax, since the function must be called one more time with empty arguments (e.g., add(1)(2)(3)()).

def add(*args):
    myArgs = []
    def f(*args):
        nonlocal myArgs         
        if len(args):          
            myArgs += args
            return f
        else:                   
            return sum(myArgs)
    return f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment