計算機科学のブログ

Building Abstractions with Functions - Formulating Abstractions with Higher-Order Functions - Functions as Arguments - 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.30の解答を求めてみる。

コード

function sum(term, a, next, b) {
    function iter(a, result) {
        return a > b ?
            result :
            iter(next(a), result + term(a));
    }
    return iter(a, 0);
}
function identity(x) {
    return x;
}
function inc(x) {
    return x + 1;
}
function square(x) {
    return x * x;
}
function add2(x) {
    return x + 2;
}

console.log(sum(identity, 1, inc, 10));
console.log(sum(identity, 1, add2, 10));
console.log(sum(identity, 2, add2, 10));
console.log(sum(square, 1, inc, 10));
console.log(sum(square, 1, add2, 10));
console.log(sum(square, 2, add2, 10));

入出力結果(Terminal, Zsh)

% node answer1.30.js
55
25
30
385
165
220
%