計算機科学のブログ

Building Abstractions with Data - Symbolic Data - Example: Representing Sets - Sets as unordered lists - union

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 unordered lists、Exercise 2.59の解答を求めてみる。

コード

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 equal(x, y) {
    return is_null(x) && is_null(y)
        ? is_pair(x) && is_pair(y) && equal(head(x), head(y)) && equal(tail(x), tail(y))
        : x === y;
}
function is_element_of_set(x, set) {
    return is_null(set)
        ? false
        : equal(x, head(set))
            ? true
            : is_element_of_set(x, tail(set));
}
function adjoin_set(x, set) {
    return is_element_of_set(x, set)
        ? set
        : pair(x, set);
}
function union_set(set1, set2) {
    return is_null(set2)
        ? set1
        : union_set(adjoin_set(head(set2), set1), tail(set2));
}

const set1 = null;
const set2 = list(1, 3, 5, 7, 9);
const set3 = list(2, 4);
const set4 = list(1, 2, 3);
const sets = list(set1, set2, set3, set4);

function iter(sets1, sets2) {
    function f(set, sets) {
        if (!is_null(sets)) {
            display(union_set(set, head(sets)));
            f(set, tail(sets));
        }
    }
    if (!is_null(sets1)) {
        const set = head(sets1);
        display("**********");
        display(set);
        f(set, sets2);
        iter(tail(sets1), sets2);
    }
}

display(sets);
iter(sets, sets);

入出力結果(Terminal, Zsh)

% node answer2.59.js
[null, [[1, [3, [5, [7, [9, null]]]]], [[2, [4, null]], [[1, [2, [3, null]]], null]]]]
**********
null
null
[9, [7, [5, [3, [1, null]]]]]
[4, [2, null]]
[3, [2, [1, null]]]
**********
[1, [3, [5, [7, [9, null]]]]]
[1, [3, [5, [7, [9, null]]]]]
[1, [3, [5, [7, [9, null]]]]]
[4, [2, [1, [3, [5, [7, [9, null]]]]]]]
[2, [1, [3, [5, [7, [9, null]]]]]]
**********
[2, [4, null]]
[2, [4, null]]
[9, [7, [5, [3, [1, [2, [4, null]]]]]]]
[2, [4, null]]
[3, [1, [2, [4, null]]]]
**********
[1, [2, [3, null]]]
[1, [2, [3, null]]]
[9, [7, [5, [1, [2, [3, null]]]]]]
[4, [1, [2, [3, null]]]]
[1, [2, [3, null]]]
%