[Edu-sig] More functional programming in Python

Kirby Urner urnerk at qwest.net
Sun Jan 11 01:46:09 EST 2004


Variations (perhaps improvements):


 >>> def compose(f,g):
        """
        Return a function f(g(x)) given two functions f,g
        """
	  return lambda x: f(g(x))

Advantage:  no mention of 'h' in resulting function





 >>> def complist(funclist):
        """
        Compose a list of functions, right to left
        """
        def e(x): return x
        if len(funclist)==0: return e
        return reduce(compose,funclist)

Advantage:  complist([]) returns identity function




 >>> def power(f,n):
 	  return complist([f] * n)


Advantage:  much simpler, makes use of complist


====

>>> def m(x):
	 return 'm(%s)' % x

	
 >>> complist([m,m,m,m])
 <function <lambda> at 0x00ADE030>

 >>> r = complist([m,m,m,m])
 >>> r(1)
 'm(m(m(m(1))))'

 >>> s = power(m,4)
 >>> s(1)
 'm(m(m(m(1))))'

 >>> s = power(m,1)
 >>> s(1)
 'm(1)'

 >>> s = power(m,0)
 >>> s(1)
 1

 >>> s('1')
 '1'

Kirby





More information about the Edu-sig mailing list