計算機科学のブログ

Building Abstractions with Data - Symbolic Data - Example: Representing Sets - Sets as binary trees - list to tree, ordered list, balanced binary tree

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 binary trees、Exercise 2.64の解答を求めてみる。

コード

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 length(x) {
    function iter(x, n) {
        return is_null(x) ?
            n :
            iter(tail(x), n + 1);
    }
    return iter(x, 0);
}
function list(...args) {
    return args.length === 0 ?
        null :
        pair(args[0], list(...args.slice(1)));
}
function is_null(x) {
    return x === null;
}
function make_tree(entry, left, right) {
    return list(entry, left, right);
}
function list_to_tree(elements) {
    return head(partial_tree(elements, length(elements)));
}
function partial_tree(elts, n) {
    if (n === 0) {
        return pair(null, elts);
    }
    const left_size = Math.floor((n - 1) / 2);
    const left_result = partial_tree(elts, left_size);
    const left_tree = head(left_result);
    const non_left_elts = tail(left_result);
    const right_size = n - (left_size + 1);
    const this_entry = head(non_left_elts);
    const right_result = partial_tree(tail(non_left_elts), right_size);
    const right_tree = head(right_result);
    const remaining_elts = tail(right_result);
    return pair(
        make_tree(this_entry, left_tree, right_tree),
        remaining_elts
    );
}

const elements = list(1, 3, 5, 7, 9, 11);
const tree = list_to_tree(elements);

display(elements);
display(tree);

入出力結果(Terminal, Zsh)

% node answer2.64.js
[1, [3, [5, [7, [9, [11, null]]]]]]
[5, [[1, [null, [[3, [null, [null, null]]], null]]], [[9, [[7, [null, [null, null]]], [[11, [null, [null, null]]], null]]], null]]]
%