curry and compose -- functional language constructs
Nick Perkins
nperkins7 at home.com
Wed May 2 02:01:11 EDT 2001
Some comments and questions on functional programming
in Python:
I learned a bit of Scheme (LISP) in school, but could never
really get any good at it. I found it fascinating, and very
powerful, but not friendly enough.
( cadr, caddr, cdaddr? --give me a break! )
( in my next life, i'll learn lisp first, ..i promise! )
On the other hand, it really made me think in new ways,
an experience similar to discovering OOP many years ago,
after knowing only BASIC.
That is one of the reasons I was attracted to Python, becuase
it could do some of those neat 'functional' things, with a
much friendlier syntax.
Recently I discovered this neat little class which
(elegantly) produces 'Curried' functions:
( sort of like partially evaluated functions )
( from activestate aspn cookbook )
class curry:
def __init__(self, fun, *args, **kwargs):
self.fun = fun
self.pending = args[:]
self.kwargs = kwargs.copy()
def __call__(self, *args, **kwargs):
if kwargs and self.kwargs:
kw = self.kwargs.copy()
kw.update(kwargs)
else:
kw = kwargs or self.kwargs
return self.fun(*(self.pending + args), **kw)
( This has the effect of taking a function and some of it's arguments,
and returning a new function (that will take the remaining arguments
when it is called ))
There is also a 'compose' python class that is very similar.
( also on aspn cookbook )
It takes 2 functions as arguments, and returns one function.
In it's simplest form:
fg = compose(f,g)
...is the same as...
def fg(x): return f(g(x))
Both are examples of functions which create and return new functions.
( technically, i suppose they are just classes with __call__ methods..
...but i am not sure what the difference is, ..i don't see much difference )
I think these are really cool, but i have never seen anyone use
curry or compose. Why not? Shouldn't everyone use these
all the time?
Does anyone have any other neat Python solutions that provide
'functional-style' features?
(aside from those built-in )
Do Python programmers generally think in a 'more functional'
way than, say, Java programmers?
Do they think in a 'less functional' way than LISP programmers?
Is Python well positioned to be the happy medium between
hard-to-understand functional languages, and more traditional languages?
--side question: what exactly do *args and **kwargs do?
-- ( i mean the asterisks )
-- it seems like they do a sort of in-place expansion/contraction..
-- i can't find any reference in the doc..
--are these forms usable outside of function parameter lists?
More information about the Python-list
mailing list