[Edu-sig] More functional programming in Python
Kirby Urner
urnerk at qwest.net
Sun Jan 11 01:24:49 EST 2004
Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)]
on win32
Type "copyright", "credits" or "license()" for more information.
****************************************************************
Personal firewall software may warn about the connection IDLE
makes to its subprocess using this computer's internal loopback
interface. This connection is not visible on any external
interface and no data is sent to or received from the Internet.
****************************************************************
IDLE 1.0.2
>>> def compose(f,g):
"""
Return a function f(g(x)) given two functions f,g
"""
def h(x):
return f(g(x))
return h
Example:
>>> def f(x): return x+1
>>> def g(x): return 2*x
>>> s = compose(f,g)
>>> s(3)
7
>>> f(g(3))
7
>>> s = compose(g,f)
>>> s(3)
8
>>> g(f(3))
8
>>> def power(f,n):
"""
Return a function of f composed with itself n times
"""
def e(x): return x # n=0 returns identity function
if n == 0: return e
r = f # n=1 returns f itself
for i in range(n-1):
r = compose(r,f)
return r
>>> f(f(f(f(f(f(f(f(f(f(1)))))))))) # f composed with itself 10 times
11
>>> t = power(f,10)
>>> t(1)
11
>>> t = power(f,0) # t = e(x), identity
>>> t(1)
1
>>> t = power(f,1) # t = f(x), i.e. f(x) = x+1 in this example
>>> t(1)
2
>>> t = power(g,5)
>>> 6*2**5 # 2 * 2 * 2 * 2 * 2 * 6
192
>>> g(g(g(g(g(6)))))
192
>>> t(6) # g(g(g(g(g(x)))))
192
>>> def complist(funclist):
"""
Compose a list of functions, right to left
"""
return reduce(compose,funclist)
>>> r = complist([g,g,f,f,g,f,g])
>>> r(17)
288
>>> g(g(f(f(g(f(g(17)))))))
288
>>> def m(x):
return 'm(%s)' % x
>>> def n(x):
return 'n(%s)' % x
>>> r = complist([m, m, n, m])
>>> r(1)
'm(m(n(m(1))))'
>>> r = power(m, 5)
>>> r(1)
'm(m(m(m(m(1)))))'
Kirby
More information about the Edu-sig
mailing list