我正在尝试使用基于SICP的在线课程来学习python和CS。我了解教会数字的基本知识,但在python中使用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."""
return lambda x: f(x)
def two(f):
"""Church numeral 2."""
return lambda x: f(f(x))
def church_to_int(n):
"""Convert the Church numeral n to a Python integer.
>>> church_to_int(zero)
0
>>> church_to_int(one)
1
>>> church_to_int(two)
2
"""
return n(lambda x: x + 1)(0)
def mul_church(m, n):
"""Return the Church numeral for m * n, for Church numerals m and n.
>>> three = successor(two)
>>> four = successor(three)
>>> church_to_int(mul_church(two, three))
6
>>> church_to_int(mul_church(three, four))
12
"""
return lambda x: m(n(x))这是我遇到麻烦的add_church函数:
def add_church(m, n):
"""Return the Church numeral for m + n, for Church numerals m and n.
>>> three = successor(two)
>>> church_to_int(add_church(two, three))
5
"""
return lambda f: lambda x: m(f(x))(n(x))我的结论是,添加教会数字的一种方法是在add_church(m,n)中有一个函数作为另一个lambda函数的输入或"x“。但是,我不断地收到错误,这意味着我在函数调用中没有使用正确的参数。
例如,当我调用:
church_to_int(add_church(one, two))我得到了一个"int对象不可调用“的错误,并尝试了其他不同的方法,但没有成功。
我认为,关于lambda函数,我没有看到一些东西,这使我在实现add_church时遇到了困难。我已经花了一段时间来弄清楚这个问题,所以任何能引导我找到答案的帮助都会受到极大的感谢。
发布于 2014-07-23 08:40:59
回想一下,教会编码可以理解为对一个论点重复应用一个函数。因此,要添加m + n,我们需要将函数f应用于参数x m + n times,或者等效地将其应用于n时间,然后将其应用于m时间:
def add_church(m, n):
def m_plus_n(f):
def f_repeated_m_plus_n_times(x) # f ** (m + n)
intermediate_result = (n(f))(x) # (f ** n) (x)
final_result = (m(f))(intermediate_result) # (f ** m) ((f ** n) (x))
return final_result
return f_repeated_m_plus_n_times
return m_plus_n在lambda格式中,删除多余的括号:
def add_church(m, n):
"""Return the Church numeral for m + n, for Church numerals m and n.
>>> three = successor(two)
>>> church_to_int(add_church(two, three))
5
"""
lambda f: lambda x: m(f)(n(f)(x))https://stackoverflow.com/questions/24905241
复制相似问题