2016-09-24 216 views
0

我不能环绕以下功能组成我的头:嵌套函数组合

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.

任何帮助,非常感谢。

非常感谢先进。

+0

为什么'λ-calculus'标签? – naomik

回答

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 
1

这可能有助于在不同的功能使用不同的参数名称不扑朔迷离起来。 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