Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Functions as General Methods - Finding fixed points of functions - infinite continued fraction, Euler's number(Napier's constant)
Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 1(Building Abstractions with Functions)、1.3(Formulating Abstractions with Higher-Order Functions)、1.3.3(Functions as General Methods)、Exercise 1.38の解答を求めてみる。
コード
function cont_frac(n, d, k) {
function iter(i, result) {
return i < 0 ?
result :
iter(i - 1, n(i) / (d(i) + result));
}
return iter(k, 0);
}
function base_of_natural_log(k) {
return cont_frac(
i => 1,
i => i % 3 === 1 ?
2 * (Math.floor(i / 3) + 1) :
1,
k
) + 2;
}
function iter(m) {
function f(k) {
if (k <= m) {
console.log(`k = ${k}: ${base_of_natural_log(k)}`);
f(k + 1);
}
}
f(0);
}
iter(20);
入出力結果(Terminal, Zsh)
% node answer1.38.js
k = 0: 3
k = 1: 2.6666666666666665
k = 2: 2.75
k = 3: 2.7142857142857144
k = 4: 2.71875
k = 5: 2.717948717948718
k = 6: 2.7183098591549295
k = 7: 2.718279569892473
k = 8: 2.718283582089552
k = 9: 2.7182817182817183
k = 10: 2.7182818352059925
k = 11: 2.7182818229439496
k = 12: 2.718281828735696
k = 13: 2.7182818284454013
k = 14: 2.718281828470584
k = 15: 2.7182818284585633
k = 16: 2.718281828459065
k = 17: 2.7182818284590278
k = 18: 2.718281828459046
k = 19: 2.718281828459045
k = 20: 2.7182818284590455
%