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
The solution from Roger Christman will not work with every constellation. I applied a small fix to also handle this situation:
curried_func(1)(2,3)
The small fix that makes it work with every constellation lies in the returned lambda:
def curried(func):
def curry(*args):
if len(args) == func.__code__.co_argcount:
ans = func(*args)
return ans
else:
return lambda *x: curry(*(args+x))
return curry
The below implementation is naive, google for "currying python" for more accurate examples.
def curry(x, argc=None):
if argc is None:
argc = x.func_code.co_argcount
def p(*a):
if len(a) == argc:
return x(*a)
def q(*b):
return x(*(a + b))
return curry(q, argc - len(a))
return p
@curry
def myfun(a,b,c):
print '%d-%d-%d' % (a,b,c)
myfun(11,22,33)
myfun(44,55)(66)
myfun(77)(88)(99)
One-liner just for fun:
from functools import partial
curry = lambda f: partial(*[partial] * f.__code__.co_argcount)(f)
@curry
def add(x, y, z):
return x + y + z
print(add(2)(3)(4))
# output = 9