Church numerals是一个很有意思的问题,cs61a的homework03中的Q7就是跟Church numerals有关的。在做这道题的过程中,我首先自己写出了代码并且测试通过,然后找了下官方的答案,没想到官方的代码如此的简短,思考之后令人不得不拍手称赞。因此,此篇文章我将分三部分:第一部分贴出我自己的代码,第二部分贴出官方的代码,第三部分会简单比较下我写的代码与官方的代码,并就官方的代码中使用的lambda方法尝试进行解读,如有错误,敬请各位批评指正。
一、我自己写的代码
def zero(f):
return lambda x: x
def successor(n):
return lambda f: lambda x: f(n(f)(x))
def one(f):
"""Church numeral 1: same as successor(zero)"""
"*** YOUR CODE HERE ***"
return lambda x: f(x)
def two(f):
"""Church numeral 2: same as successor(successor(zero))"""
"*** YOUR CODE HERE ***"
return lambda x: f(f(x))
three = successor(two)
def church_to_int(n):
"""Convert the Church numeral n to a Python integer."""
"*** YOUR CODE HERE ***"
i = 0
temp = zero
while n(lambda x: x+1)(0) != temp(lambda x: x+1)(0):
i += 1
temp = successor(temp)
return i
def add_church(m, n):
"""Return the Church numeral for m + n, for Church numerals m and n."""

本文探讨了cs61a homework03中关于Church numerals的问题,作者分享了自己的实现和官方简洁的解决方案。通过比较和分析,解释了官方代码中lambda函数的精妙之处,涉及church_to_int、add_church、mul_church和pow_church四个函数。
最低0.47元/天 解锁文章
1016





