計算機科学のブログ

Building Abstractions with Functions - Functions and the Processes They Generate - Exponentiation - integer multiplication

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.4(Exponentiation)、Exercise 1.17の解答を求めてみる。

コード

function double(x) {
    return 2 * x;
}
function halve(x) {
    return x / 2;
}
function times(a, b) {
    function iter(n, result) {
        return n === b ?
            result :
            iter(n + 1, a + result);
    }
    return iter(0, 0);
}
function p(a, b) {
    console.log(times(a, b), times(b, a));
}

p(0, 0);
p(0, 10);
p(1, 1);
p(1, 2);
p(5, 8);

入出力結果(Terminal, Zsh)

% node answer1.17.js
0 0
0 0
1 1
2 2
40 40
%