Created
October 6, 2015 05:13
-
-
Save codeadict/3413801f2fcfd9318da7 to your computer and use it in GitHub Desktop.
My modest Python currying implementation using a decorator. Currying is a kind of incremental binding of function arguments.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def currify(func): | |
""" | |
Decorator to curry a function, use it like this: | |
>>> @currify | |
... def sum(a, b, c): | |
... return a + b + c | |
It works on normal way: | |
>>> sum(1, 2, 3) | |
6 | |
And also binding the params: | |
>>> sum(1)(2, 3) | |
6 | |
>>> sum(1)(2)(3) | |
6 | |
Also you can provide named arguments: | |
>>> sum(a=1)(b=2)(c=3) | |
6 | |
>>> sum(b=1)(c=2)(a=3) | |
6 | |
>>> sum(a=1, b=2)(c=3) | |
6 | |
>>> sum(a=1)(b=2, c=3) | |
6 | |
""" | |
def curried(*args, **kwargs): | |
if len(args) + len(kwargs) >= func.__code__.co_argcount: | |
return func(*args, **kwargs) | |
return (lambda *args2, **kwargs2: | |
curried(*(args + args2), **dict(kwargs, **kwargs2))) | |
return curried |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment