Partially evaluated functions
Nick Perkins
nperkins7 at home.com
Wed Jun 20 23:32:48 EDT 2001
"Alex Martelli" <aleaxit at yahoo.com> wrote...
> ...
> from __future__ import nested_scopes
>
> def curry(func, *args, **kwds):
> def callit(*moreargs, **morekwds):
> morekwds.update(kwds)
> return func(*(moreargs+args), **morekwds)
> return callit
> ...
Sweet. I liked it so much I had to do some speed-tests:
I used the following:
( supplies args left-to-right, with call-time kw args trumping create-time
kw args )
from __future__ import nested_scopes
def curry(func, *args, **kwds):
def curried_function(*moreargs, **morekwds):
kwds.update(morekwds)
return func(*(args+moreargs), **kwds)
return curried_function
...and tested this against a class-implementation of curry:
( avoiding any dict.copy()...)
class curry_class:
def __init__(self, func, *args, **kwds):
self.func = func
self.args = args
self.kwds = kwds
def __call__(self, *moreargs, **morekwds):
self.kwds.update(morekwds)
return self.func(*(self.args + moreargs), **self.kwds)
I used both of these to create some curried functions, and some nested
curries,
e.g.
curry(curry(fn,arg1),arg2)
..
and then timed calling them many times.
I found that the function-version is significantly faster than the
class-version, in fact, almost twice as fast in the tests that I ran.
Cool stuff. Nested scopes rule.
More information about the Python-list
mailing list