計算機科学のブログ

Building Abstractions with Data - Symbolic Data - Example: Representing Sets - Sets as ordered lists - union set, ordered lists

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.3(Symbolic Data)、2.3.3(Example: Representing Sets)、Sets as ordered lists、Exercise 2.62の解答を求めてみる。

コード

function stringfy(x) {
    if (is_null(x)) {
        return "null";
    }
    if (is_pair(x)) {
        return "[" + stringfy(head(x)) + ", " + stringfy(tail(x)) + "]";
    }
    if (x === undefined) {
        return "undefined";
    }
    return x.toString();
}
function display(x) {
    return console.log(stringfy(x));
}
function pair(x, y) {
    return [x, y];
}
function head(z) {
    return z[0];
}
function tail(z) {
    return z[1];
}
function is_pair(x) {
    return Array.isArray(x);
}
function list(...args) {
    return args.length === 0 ?
        null :
        pair(args[0], list(...args.slice(1)));
}
function is_null(x) {
    return x === null;
}
function union_set(set1, set2) {
    if (is_null(set1)) {
        return set2;
    }
    if (is_null(set2)) {
        return set1;
    }
    const elem1 = head(set1);
    const elem2 = head(set2);
    return elem1 < elem2
        ? pair(elem1, union_set(tail(set1), set2))
        : elem1 === elem2
            ? pair(elem1, union_set(tail(set1), tail(set2)))
            : pair(elem2, union_set(set1, tail(set2)));
}
const set1 = list(1, 3, 4, 5, 7, 9);
const set2 = list(2, 4, 6, 7, 8, 10);

display(set1);
display(set2);
display(union_set(set1, set2));

入出力結果(Terminal, Zsh)

% node answer2.62.js
[1, [3, [4, [5, [7, [9, null]]]]]]
[2, [4, [6, [7, [8, [10, null]]]]]]
[1, [2, [3, [4, [5, [6, [7, [8, [9, [10, null]]]]]]]]]]
%