在python中使用lambda函数添加教堂数字

时间:2014-07-23 08:18:37

标签: python lambda church-encoding

我正在尝试使用基于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)中的一个函数作为输入或者" x"在另一个人的lambda函数中。但是,我不断收到错误,暗示我在函数调用中没有使用正确的参数。

例如,当我打电话时:

church_to_int(add_church(one, two))

我得到一个" int对象不可调用"其他错误,并尝试了其他不同的方法,但没有成功。

我认为有些东西我没有看到lambda函数导致我在实现add_church时遇到问题。我已经花了一段时间来搞清楚这一点,所以我将非常感谢任何帮助我找到答案的帮助。

1 个答案:

答案 0 :(得分:3)

回想一下,教会编码可以理解为对参数重复应用函数。因此,要添加m + n,我们需要将函数f应用于参数x m + n次,或等效地应用n次,然后应用它{ {1}}次:

m

以lambda形式删除多余的括号:

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