計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Hierarchical Structures - Mapping over trees - square tree, abstraction

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.31の解答を求めてみる。

コード

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 display(x) {
    return console.log(stringfy(x));
}
function square(x) {
    return x * x;
}
function tree_map(f, tree) {
    return map(
        sub_tree =>
            is_pair(sub_tree) ?
                square_tree(sub_tree) :
                f(sub_tree),
        tree
    );
}
function square_tree(tree) {
    return tree_map(square, tree);
}
const tree = list(
    1,
    list(
        2,
        list(
            3,
            4
        ),
        5),
    list(
        6,
        7
    )
);


display(tree);
display(square_tree(tree));

入出力結果(Terminal, Zsh)

% node answer2.31.js
[1, [[2, [[3, [4, null]], [5, null]]], [[6, [7, null]], null]]]
[1, [[4, [[9, [16, null]], [25, null]]], [[36, [49, null]], null]]]
%