Question
I am trying to write a currying decorator as @curry in python so the function can be:
- @curry
- def myfun(a,b,c):
- print("{}-{}-{}".format(a,b,c))
- myfun(1, 2, 3)
- myfun(1, 2)(3)
- myfun(1)(2)(3)
If you are using Python2:
- 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)
- from inspect import signature
- def curry(x, argc=None):
- if argc is None:
- argc = len(signature(x).parameters)
- 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("{}-{}-{}".format(a,b,c))
- myfun(1, 2, 3)
- myfun(1, 2)(3)
- myfun(1)(2)(3)
Supplement
* How can I find the number of arguments of a Python function?
沒有留言:
張貼留言