Naming higher order functions
Jonathan Hogg
jonathan at onegoodidea.com
Fri Feb 1 11:32:28 EST 2002
On 31/1/2002 18:56, in article 3c59901d_2 at corp.newsgroups.com, "Joshua
Muskovitz" <joshm at taconic.net> wrote:
>> "Erno Kuusela" <erno-news at erno.iki.fi> wrote in message
>> news:kuelk63747.fsf at lasipalatsi.fi...
>>> what would be a good name for the following function?
>>>
>>> def name_me(n):
>>> def g(x):
>>> return x[n]
>>> return g
>
> "RefactorMe"
def curry( f, *xs ):
return lambda *ys: f( *xs+ys )
def get_nth_item( n, x ):
return x[n]
get_5th_item = curry( get_nth_item, 5 )
(for a suitable definition of "nth" where 0th comes first...)
If you're not an FP-head then you might prefer (also more complete):
def partial_apply( f, args, keys={} ):
if not callable(f):
raise TypeError( "'%s' object is not callable" % type(f).__name__ )
targs = tuple(args)
tkeys = dict(keys)
def tempf( *nargs, **nkeys ):
tkeys.update( nkeys )
return f( *targs + nargs, **tkeys )
return tempf
get_5th_item = partial_apply( get_nth_item, (5,) )
Jonathan
More information about the Python-list
mailing list