PythonCurry

Python Curry

24 July 2008

See the wikipedia article on Currying for an explanation of the basic concept.

Update: The initial version (see history) had a fatal flaw—the argument list was shared between all versions of the curried function. The new version fixes this (and adds better testing :).

=python """An attempt at implementing currying in Python.""" import inspect class Curry(object): def __init__(self, func, arg_names=None, arg_values=None): self.func = func if arg_names is None: args, varargs, varkw, defaults = inspect.getargspec(self.func) self.arg_names = args else: self.arg_names = arg_names if arg_values is None: self.arg_values = () else: self.arg_values = arg_values def __call__(self, *params): new_params = self.arg_values + params if len(new_params) >= len(self.arg_names): return self.func(*new_params) else: return Curry(self.func, arg_names=self.arg_names, arg_values=new_params) if __name__ == "__main__": print "Running some basic tests ..." def f(x,y): return x + y cf = Curry(f) cf_5 = cf(5) cf_10 = cf(10) assert cf(5)(6) == 11 assert cf_5(7) == 12 assert cf_10(12) == 22 def g(x,y,z,w): return (x - y) + (z - w) cg = Curry(g) cg_2_1 = cg(2)(1) cg_3_4_5 = cg(3)(4)(5) cg_12 = cg(12) assert cg(4)(3)(2)(1) == 2 assert cg_2_1(7)(5) == 3 assert cg_3_4_5(12) == -8 assert cg_12(2)(8)(4) == 14 ---- (:commentboxchrono:)

Edit - History - Print - Recent Changes - Search
Page last modified on July 26, 2008, at 12:12 PM