計算機科学のブログ

Building Abstractions with Functions - Functions and the Processes They Generate - Exponentiation - iterative process for multiplying two integers

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

コード

function is_even(n) {
    return n % 2 === 0;
}
function double(x) {
    return 2 * x;
}
function halve(x) {
    return x / 2;
}
function mul(a, b) {
    function iter(a, b, c) {
        return b === 0 ?
            c :
            is_even(b) ?
                iter(double(a), halve(b), c) :
                iter(a, b - 1, c + a);
    }
    return iter(a, b, 0);
}

function log(a, b) {
    console.log(`${a} x ${b} = ${mul(a, b)}`)
    console.log(`${b} x ${a} = ${mul(b, a)}`)
}

log(0, 0);
log(0, 1);
log(1, 1);
log(1, 2);
log(1, 10);
log(2, 4);
log(2, 5);
log(3, 5);
log(10, 20);
log(10, 21);
log(11, 20);
log(11, 21);

入出力結果(Terminal, Zsh)

% node answer1.18.js
0 x 0 = 0
0 x 0 = 0
0 x 1 = 0
1 x 0 = 0
1 x 1 = 1
1 x 1 = 1
1 x 2 = 2
2 x 1 = 2
1 x 10 = 10
10 x 1 = 10
2 x 4 = 8
4 x 2 = 8
2 x 5 = 10
5 x 2 = 10
3 x 5 = 15
5 x 3 = 15
10 x 20 = 200
20 x 10 = 200
10 x 21 = 210
21 x 10 = 210
11 x 20 = 220
20 x 11 = 220
11 x 21 = 231
21 x 11 = 231
%