2016-09-24 129 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