|
Revision 385, 1.3 kB
(checked in by simon, 4 years ago)
|
|
Remove unused import.
|
-
Property svn:mime-type set to
text/python-source
-
Property svn:eol-style set to
native
|
| Line | |
|---|
| 1 | """An attempt at implementing currying in Python.""" |
|---|
| 2 | |
|---|
| 3 | import inspect |
|---|
| 4 | |
|---|
| 5 | class Curry(object): |
|---|
| 6 | def __init__(self, func, arg_names=None, arg_values=None): |
|---|
| 7 | self.func = func |
|---|
| 8 | |
|---|
| 9 | if arg_names is None: |
|---|
| 10 | args, varargs, varkw, defaults = inspect.getargspec(self.func) |
|---|
| 11 | self.arg_names = args |
|---|
| 12 | else: |
|---|
| 13 | self.arg_names = arg_names |
|---|
| 14 | |
|---|
| 15 | if arg_values is None: |
|---|
| 16 | self.arg_values = () |
|---|
| 17 | else: |
|---|
| 18 | self.arg_values = arg_values |
|---|
| 19 | |
|---|
| 20 | def __call__(self, *params): |
|---|
| 21 | new_params = self.arg_values + params |
|---|
| 22 | if len(new_params) >= len(self.arg_names): |
|---|
| 23 | return self.func(*new_params) |
|---|
| 24 | else: |
|---|
| 25 | return Curry(self.func, arg_names=self.arg_names, |
|---|
| 26 | arg_values=new_params) |
|---|
| 27 | |
|---|
| 28 | if __name__ == "__main__": |
|---|
| 29 | print "Running some basic tests ..." |
|---|
| 30 | |
|---|
| 31 | def f(x,y): |
|---|
| 32 | return x + y |
|---|
| 33 | cf = Curry(f) |
|---|
| 34 | |
|---|
| 35 | cf_5 = cf(5) |
|---|
| 36 | cf_10 = cf(10) |
|---|
| 37 | |
|---|
| 38 | assert cf(5)(6) == 11 |
|---|
| 39 | assert cf_5(7) == 12 |
|---|
| 40 | assert cf_10(12) == 22 |
|---|
| 41 | |
|---|
| 42 | def g(x,y,z,w): |
|---|
| 43 | return (x - y) + (z - w) |
|---|
| 44 | cg = Curry(g) |
|---|
| 45 | |
|---|
| 46 | cg_2_1 = cg(2)(1) |
|---|
| 47 | cg_3_4_5 = cg(3)(4)(5) |
|---|
| 48 | cg_12 = cg(12) |
|---|
| 49 | |
|---|
| 50 | assert cg(4)(3)(2)(1) == 2 |
|---|
| 51 | assert cg_2_1(7)(5) == 3 |
|---|
| 52 | assert cg_3_4_5(12) == -8 |
|---|
| 53 | assert cg_12(2)(8)(4) == 14 |
|---|