計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Hierarchical Structures - Mapping over trees - list, set, subsets

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.2(Hierarchical Data and the Closure Property)、2.2.2(Hierarchical Structures)、Mapping over trees、Exercise 2.32の解答を求めてみる。

コード

function stringfy(x) {
    if (is_null(x)) {
        return "null";
    }
    if (is_pair(x)) {
        return "[" + stringfy(head(x)) + ", " + stringfy(tail(x)) + "]";
    }
    return x.toString();
}
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 is_null(x) {
    return x === null;
}
function list(...args) {
    return args.length === 0 ?
        null :
        pair(args[0], list(...args.slice(1)));
}
function map(f, items) {
    return is_null(items) ?
        null :
        pair(f(head(items)), map(f, tail(items)));
}
function append(list1, list2) {
    return is_null(list1) ?
        list2 :
        pair(head(list1), append(tail(list1), list2));
}
function display(x) {
    return console.log(stringfy(x));
}
function subsets(s) {
    if (is_null(s)) {
        return list(null);
    }
    const rest = subsets(tail(s));
    return append(
        rest,
        map(
            x => pair(head(s), x),
            rest
        )
    );
}
const s = list(1, 2, 3);

display(
    subsets(s)
);

入出力結果(Terminal, Zsh)

% node answer2.32.js
[null, [[3, null], [[2, null], [[2, [3, null]], [[1, null], [[1, [3, null]], [[1, [2, null]], [[1, [2, [3, null]]], null]]]]]]]]
%