PythonCurryHstarWeblog.PythonCurry HistoryShow minor edits - Show changes to markup July 26, 2008, at 12:12 PM
by - Fixed fatal flaw.
Added lines 6-7:
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 :). Changed lines 9-10 from:
to:
"""An attempt at implementing currying in Python.""" 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, 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
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:
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
July 24, 2008, at 03:30 PM
by - Curry?
Added lines 1-36:
Python Curry24 July 2008 See the wikipedia article on 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) |