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?
2 Answers 2
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.
-
1Actually this is a great answer! Overloading call is a creative solution that I wouldn't have even thought of. So to do this for another class, I would just define a call function for it, that uses the value of self to return the same class, but also is a function! That's exactly what I was hoping for!vikarjramun– vikarjramun2016年08月25日 00:15:37 +00:00Commented Aug 25, 2016 at 0:15
-
"but also is a function" isn't the exact terminology i'd use :-P. It is also callable, that is, it can behave as a function, that's really all we need here.Dimitris Fasarakis Hilliard– Dimitris Fasarakis Hilliard2016年08月25日 01:53:38 +00:00Commented Aug 25, 2016 at 1:53
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.
-
Can you define a lambada with an optional parameter? Or one with a default?vikarjramun– vikarjramun2016年08月24日 12:09:23 +00:00Commented Aug 24, 2016 at 12:09
-
Explore related questions
See similar questions with these tags.
addByCurrying(1)(2)
is both a number and a function, which isn't possible.(lambda x: x (x)) ((lambda a: lambda b: lambda c: a (b)) (lambda x: x (x)))
takes an argument and returns a new instance of itself, meaning you can pass as much arguments as you want.