Building Abstractions with Functions - Functions and the Processes They Generate - Tree Recursion - Pascal's triangle, recursive process
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.2(Functions and the Processes They Generate)、1.2.2(Tree Recursion)、Exercise 1.12の解答を求めてみる。
コード
function pascal_triangle(m, n) {
return n === 1 || m === n ?
1 :
pascal_triangle(m - 1, n - 1) + pascal_triangle(m - 1, n);
}
function log_m(m) {
function iter(n) {
if (n <= m) {
console.log(pascal_triangle(m, n));
iter(n + 1);
}
}
console.log(`m = ${m}`);
iter(1);
}
function log(m_max) {
function iter(m) {
if (m <= m_max) {
log_m(m);
iter(m + 1);
}
}
iter(1);
}
log(10);
入出力結果(Terminal, Zsh)
% node answer1.12.js
m = 1
1
m = 2
1
1
m = 3
1
2
1
m = 4
1
3
3
1
m = 5
1
4
6
4
1
m = 6
1
5
10
10
5
1
m = 7
1
6
15
20
15
6
1
m = 8
1
7
21
35
35
21
7
1
m = 9
1
8
28
56
70
56
28
8
1
m = 10
1
9
36
84
126
126
84
36
9
1
%