Function composition

Michael Hudson mwh21 at cam.ac.uk
Wed Aug 2 18:26:41 EDT 2000


cg at gaia.cdg.acriter.nl (Cees de Groot) writes:

> I was showing a Math PhD/Functional programming guy Python, and of
> course he was interested in map, filter, etcetera. He talked about
> function composition, and I did a quick:
> 
> def compose(f, g): return lambda x: f(g(x))
> 
> but that's of course only for single-argument functions. My
> advanced-Python-hacking seems to be getting rusty (too much Java
> coding, sorry for that), but is there an easy way to extend this to
> any argument signature?

Well, you could do

class compose:
    def __init__(self,f,g):
        self.f = f
        self.g = g
    def __call__(self,*args,**kw):
        return self.f(apply(self.g,args,kw))

but that only works for single argument f.  As Python doesn't have
multiple return values, I can't see a way around this (yes, you could
arrange things so that if g returned a tuple, then the elements of the
tuple were the arguments passed to f, but that's at best unclean).

Note that in Haskell, you can only compose functions of one argument
(but then in Haskell you can only have functions of one argument!).

cl:multiple-value-call-ly yr's
Michael

-- 
  If i don't understand lisp,  it would be wise to not bray about
  how lisp is stupid or otherwise criticize, because my stupidity 
  would be archived and open for all in the know to see.
                                                -- Xah, comp.lang.lisp



More information about the Python-list mailing list