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