Hypothetical situation - can a currying function have an unknown number of arguments (kind of like varargs) Eg in Python:
addByCurrying(1)(2)(3)(4)
Should equal 10
addByCurrying(5)(6)
Should equal 11
How could I implement it?
Hypothetical situation - can a currying function have an unknown number of arguments (kind of like varargs) Eg in Python:
addByCurrying(1)(2)(3)(4)
Should equal 10
addByCurrying(5)(6)
Should equal 11
How could I implement it?
I recently answered a question on S.O regarding this exact situation. You can't do this with traditional functions in Python.
You can do this by taking advantage of callables though, overloading the __call__
dunder of an int
subclass.
In short, return a new instance of your self with the updated value (+
here):
class addByCallable(int):
def __call__(self, v):
return type(self)(self + v)
Now, you call it and get this 'form' of currying:
addByCallable(1)(2)(3) # 6
Which is as close as you can get to doing this in Python.
This is not possible since there is no way the function could know if it should return a number or a curried function.
There are various way of "cheating" to achieve some thing somewhat like this, for example you could call with no arguments in order to get the number rather than a function:
addByCurrying(1)(2) --> curried function
addByCurrying(1)(2)() --> the number 3
Which trick is most appropriate depends on what you are trying to achieve.