計算機科学のブログ

Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Functions as Arguments - product, linear recursion, iteration

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.1(Functions as Arguments)、Exercise 1.31の解答を求めてみる。

コード

function inc(x) {
    return x + 1;
}
function identity(x) {
    return x;
}
function square(x) {
    return x * x;
}
console.log('a.');
function product(term, a, next, b) {
    return a > b ?
        1 :
        term(a) * product(term, next(a), next, b);
}

function factorial(n) {
    return product(identity, 1, inc, n);
}
console.log('n!');
console.log(factorial(0));
console.log(factorial(1));
console.log(factorial(2));
console.log(factorial(3));
console.log(factorial(4));
console.log(factorial(5));
console.log(factorial(6));
console.log(factorial(7));
console.log(factorial(8));
console.log(factorial(9));
console.log(factorial(10));

function pi(n) {
    function term(n) {
        let a = 2 * n + 2,
            b = 2 * n + 3;

        return a * (a + 2) / (b * b);
    }
    return 4 * product(term, 0, inc, n);
}

console.log('π');
console.log(pi(1));
console.log(pi(2));
console.log(pi(3));
console.log(pi(4));
console.log(pi(5));
console.log(pi(5));
console.log(pi(10));
console.log(pi(100));
console.log(pi(1000));

console.log('b.');

function product1(term, a, next, b) {
    function iter(n, result) {
        return n > b ?
            result :
            iter(next(n), result * term(n));
    }
    return iter(a, 1);
}
function factorial1(n) {
    return product1(identity, 1, inc, n);
}

console.log('n!');
console.log(factorial1(0));
console.log(factorial1(1));
console.log(factorial1(2));
console.log(factorial1(3));
console.log(factorial1(4));
console.log(factorial1(5));
console.log(factorial1(6));
console.log(factorial1(7));
console.log(factorial1(8));
console.log(factorial1(9));
console.log(factorial1(10));

function pi1(n) {
    function term(n) {
        let a = 2 * n + 2,
            b = 2 * n + 3;

        return a * (a + 2) / square(b);
    }
    return 4 * product1(term, 0, inc, n);
}

console.log('π');
console.log(pi1(1));
console.log(pi1(2));
console.log(pi1(3));
console.log(pi1(4));
console.log(pi1(5));
console.log(pi1(5));
console.log(pi1(10));
console.log(pi1(100));
console.log(pi1(1000));

入出力結果(Terminal, Zsh)

% node answer1.31.js
a.
n!
1
1
2
6
24
120
720
5040
40320
362880
3628800
π
3.413333333333333
3.343673469387755
3.302393550012597
3.275101041334807
3.2557217452322336
3.2557217452322336
3.207709732466547
3.1493020486382037
3.1423765818510354
b.
n!
1
1
2
6
24
120
720
5040
40320
362880
3628800
π
3.413333333333333
3.343673469387755
3.302393550012597
3.2751010413348074
3.2557217452322345
3.2557217452322345
3.207709732466548
3.1493020486382033
3.142376581851035
%