PythonCurryHstarWeblog.PythonCurry HistoryShow minor edits - Show changes to output July 26, 2008, at 12:12 PM
by
- Fixed fatal flaw.Added lines 6-7:
'''Update''': The initial version (see [[{$PageUrl}?action=diff|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 :). Changed lines 9-10 from:
# An attempt at implementing currying in Python. to:
Changed lines 14-24 from:
def __init__(self, f): args, varargs, varkw, defaults = inspect.getargspec(f) self._f = f self._n = len(args) self._arg_values = [] def __call__(self, *args): self._arg_values.extend(args) if len(self._arg_values) >= self._n: return self._f(*self._arg_values) to:
def __init__(self, args, varargs, varkw, defaults self.func = args, varargs, varkw, defaults = self._n = len self._arg_values self.arg_names = def __call__(self, *args): self._arg_values.extend(args) if len(self._arg_values) >= self._n: return self._f(*self._arg_values) Changed lines 21-32 from:
return self def f(x,y): return x + y cf = Curry(f) print cf(5)(6) def g(x,y,z,w): return (x - y) + (z - w) cg = Curry(g) print cg(6)(5)(4)(3) to:
return x + y cf self.arg_values = print cf(5)(6) else: self.arg_values = arg_values return (x - y) new_params = self.arg_values + if len(new_params) cg = Curry return self.func(*new_params) print cg else: return Curry( 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 July 24, 2008, at 03:30 PM
by
- Curry?Added lines 1-36:
!!Python Curry [-24 July 2008-] See the wikipedia article on [[wikipedia:Currying|Currying]] for an explanation of the basic concept. =python [= # An attempt at implementing currying in Python. import inspect class Curry(object): def __init__(self, f): args, varargs, varkw, defaults = inspect.getargspec(f) self._f = f self._n = len(args) self._arg_values = [] def __call__(self, *args): self._arg_values.extend(args) if len(self._arg_values) >= self._n: return self._f(*self._arg_values) else: return self def f(x,y): return x + y cf = Curry(f) print cf(5)(6) def g(x,y,z,w): return (x - y) + (z - w) cg = Curry(g) print cg(6)(5)(4)(3) =] |