計算機科学のブログ

Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Functions as Arguments - Simpson's Rule

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.29の解答を求めてみる。

コード

function cube(x) {
    return x * x * x;
}
function sum(term, a, next, b) {
    return a > b ?
        0 :
        term(a) + sum(term, next(a), next, b);
}
function simpson_rule(f, a, b, n) {
    let h = (b - a) / n;

    function y(k) {
        return f(a + k * h);
    }
    function term(k) {
        return (
            k === 0 || k === n ?
                1 :
                k % 2 === 0 ?
                    2 :
                    4
        ) * y(k);
    }
    function next(k) {
        return k + 1;
    }
    return h / 3 * sum(term, 0, next, n);
}

function p(n) {
    return simpson_rule(cube, 0, 1, n);
}

console.log('n = 100');
console.log(p(100));
console.log('n = 1000');
console.log(p(1000));

入出力結果(Terminal, Zsh)

% node answer1.29.js
n = 100
0.24999999999999992
n = 1000
0.2500000000000003
%