【问题标题】:Nested Function Composition嵌套函数组合
【发布时间】:2016-09-24 10:10:02
【问题描述】:

我无法理解以下函数组合:

function plus_one(x) {
    return x + 1;
}

function trans(f) {
    return function(x) {
        return 2 * f(2 * x);
    };
}

function twice(f) {
    return function(x) {
        return f(f(x));
    }
}

当我尝试评估((twice)(trans))(plus_one)(1) 这就是我得到的,假设 plus_one 是 f

f(2f(2x))=2f(2*2f(2x))=2f(4f(2x)) = 2*(4*(2 + 1)) = 24.

但是在解释器中输入它会显示它是 20。

【问题讨论】:

  • 为什么是lambda-calculus 标签?

标签: functional-programming lambda-calculus


【解决方案1】:

((twice)(trans))(plus_one)trans(trans(plus_one)),并且

trans(trans(plus_one)) (1)
—> trans(λx.2 * plus_one(2*x)) (1)
—> λy.2 * ((λx.2 * plus_one(2*x))(2*y) (1)
—> 2 * (λx.2 * plus_one(2*x)) (2*1)
-> 2 * 2 * plus_one(2*2)
-> 2 * 2 * 5
-> 20

【讨论】:

    【解决方案2】:

    在不同的函数中使用不同的参数名称可能有助于避免混淆它们。 f 并不总是指代plus_one

    plus_one = λ x0 ⇒ x0 + 1;
    trans = λ f0 ⇒ λ x1 ⇒ 2 * f0(2 * x1);
    twice = λ f1 ⇒ λ x2 ⇒ f1(f1(x2));
    

    我们可以评估

    twice(trans)(plus_one)(1)
    

    作为

    ≡ (λ f1 ⇒ λ x2 ⇒ f1(f1(x2)))(trans)(plus_one)(1)
    ≡ (λ x2 ⇒ trans(trans(x2)))(plus_one)(1)
    ≡ trans(trans(plus_one)))(1)
    ≡ (λ f0 ⇒ λ x1 ⇒ 2 * f0(2 * x1))(trans(plus_one)))(1)
    ≡ (λ x1 ⇒ 2 * trans(plus_one)(2 * x1))(1)
    ≡ 2 * trans(plus_one)(2 * 1)
    ≡ 2 * (λ f0 ⇒ λ x1 ⇒ 2 * f0(2 * x1))(plus_one)(2 * 1)
    ≡ 2 * (λ x1 ⇒ 2 * plus_one(2 * x1))(2 * 1)
    ≡ 2 * 2 * plus_one(2 * (2 * 1))
    ≡ 2 * 2 * (λ x0 ⇒ x0 + 1)(2 * (2 * 1))
    ≡ 2 * 2 * ((2 * (2 * 1)) + 1)
    ≡ 20
    

    【讨论】:

      【解决方案3】:

      符号就是一切。

      plus_one(x) = (x + 1)
      trans(f)(x) = 2 * f(2 * x)
      twice(f)(x) = f(f(x))
      
      twice(trans)(plus_one)(1)
      =
      trans(trans(plus_one))(1)
      =
      2 * (trans(plus_one))(2 * 1)
      =
      2 * trans(plus_one)(2)
      =
      2 * (2 * plus_one(2 * 2))
      =
      2 * (2 * (4 + 1))
      =
      20
      

      另见:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-26
        • 2020-11-06
        • 1970-01-01
        • 2019-12-22
        • 1970-01-01
        • 2019-05-26
        • 1970-01-01
        相关资源
        最近更新 更多