用不动点组合子解递归(python实现)
不动点组合子
Y = λf. (λx. f (x x)) (λx. f (x x))
θ = (λx. λy. (y(x x y))) (λx.λy.(y(x x y)))
Y f = f (Y f)
θ f = f (θ f)
设
h1 =λx.f(x x)
h2 =λx.λy.(y(x x y))
简化为:
Y = λf. h1(h1)
θ = h2(h2)
递归求解
ƒ(n) = n*ƒ(n-1)
ƒ(0) = 1
简记为: ƒ = λn.n׃(n-1) #ƒ对应代码中的 factorial
用归纳法可证ƒ唯一,
设 g = λƒ.λn.n׃(n-1) #g对应代码中的_factorial
则g ƒ = λn.n׃(n-1) = ƒ
因为g(Y g)=(Y g)
所以Y g为ƒ的唯一解
即ƒ(n)=(Y g)(n)=(Θ g)(n)
def _factorial(f):
def factorial(n):
if not n:
return 1
else:
return n * f(n - 1)
return factorial
def Y(f):
def h(x):
return f(lambda v: x(x)(v))
return h(h)
def O(f):
def h(x):
return (lambda y: y(lambda v: x(x)(y)(v)))
return h(h)(f)
#Y(_factorial)(5)
#O(_factorial)(5)
#Y = lambda f: (lambda x:f(lambda v:x(x)(v)))(lambda x:f(lambda v:x(x)(v)))
#YY = lambda f: ((lambda x: x(x))(lambda y: f(lambda v: y(y)(v))))
参考:
http://www.cnblogs.com/ldp615/archive/2013/04/09/recursive-lambda-expressions-1.html
http://www.cnblogs.com/ldp615/archive/2013/04/09/recursive-lambda-expressions-2.html
http://www.cnblogs.com/ldp615/archive/2013/04/10/recursive-lambda-expressions-3.html
http://www.cnblogs.com/ldp615/archive/2013/04/10/recursive-lambda-expressions-4.html
http://www.cnblogs.com/ldp615/archive/2013/04/11/recursive-lambda-expressions-5.html
http://www.pythontip.com/blog/post/12174/