-
-
Save rctay/1226563 to your computer and use it in GitHub Desktop.
[fork] currying in python (from http://pydroid.posterous.com/nextpy-currying)
This file contains hidden or 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
""" | |
See also: | |
- http://code.activestate.com/recipes/52549/#c6 | |
- http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application | |
""" | |
class curry: | |
def __init__(self, fun): | |
import inspect | |
self.fun = fun | |
self.__args = [] | |
self.min_arg_count = len(inspect.getargspec(fun)[0]) | |
def __call__(self, one): | |
args = self.__args + [one, ] | |
# enough args, call fun | |
if len(args) >= self.min_arg_count: | |
return self.fun(*args) | |
# not enough args, return a new curried instance | |
ret = curry(self.fun) | |
ret.__args = args | |
return ret | |
def myMax(x,y): | |
return x if x > y else y | |
def third_of(a, b, c): | |
return c | |
if __name__ == "__main__": | |
max_of_4 = curry(myMax)(4) | |
print max_of_4(2) # max(4,2) = 4 | |
print max_of_4(6) # max(4,6) = 6 | |
print curry(third_of)(1) | |
print curry(third_of)(1)(2) | |
print curry(third_of)(1)(2)(3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment