計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Hierarchical Structures - Mapping over trees - recursion

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

コード

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;
}
const tree = list(
    1,
    list(
        2,
        list(
            3,
            4
        ),
        5),
    list(
        6,
        7
    )
);

display(tree);

function square_tree1(tree) {
    return is_null(tree) ?
        null :
        !is_pair(tree) ?
            square(tree) :
            pair(
                square_tree1(head(tree)),
                square_tree1(tail(tree))
            );
}

display(square_tree1(tree));

function square_tree2(tree) {
    return map(
        sub_tree =>
            is_pair(sub_tree) ?
                square_tree2(sub_tree) :
                square(sub_tree),
        tree
    );
}

display(square_tree2(tree));

入出力結果(Terminal, Zsh)

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