計算機科学のブログ

Building Abstractions with Data - Introduction to Data Abstraction - What Is Meant by Data? - nonnegative integers

Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 2(Building Abstractions with Data)、2.1(Introduction to Data Abstraction)、2.1.3(What Is Meant by Data?)、Exercise 2.5の解答を求めてみる。

コード

function expt(a, b) {
    return b === 0 ?
        1 :
        a * expt(a, b - 1);
}
function int_pair(a, b) {
    return expt(2, a) * expt(3, b);
}
function int_head(p) {
    function iter(p, count) {
        return p % 2 === 0 ?
            iter(p / 2, count + 1) :
            count;
    }
    return iter(p, 0);
}
function int_tail(p) {
    function iter(p, count) {
        return p % 3 === 0 ?
            iter(p / 3, count + 1) :
            count;
    }
    return iter(p, 0);
}

const n = int_pair(2, 3);
console.log(n);
console.log(int_head(n));
console.log(int_tail(n));

const m = int_pair(16, 11);
console.log(m);
console.log(int_head(m));
console.log(int_tail(m));

入出力結果(Terminal, Zsh)

% node answer2.5.js
108
2
3
11609505792
16
11
%