計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Representing Sequences - Mapping over lists - list of squares

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.1(Representing Sequences)、Mapping over lists、Exercise 2.21の解答を求めてみる。

コード

function stringfy(x) {
    return x.toString();
}
function pair(x, y) {
    return [x, y];
}
function head(z) {
    return z[0];
}
function tail(z) {
    return z[1];
}
function list(...args) {
    return args.length === 0 ?
        null :
        pair(args[0], list(...args.slice(1)));
}
function print_list(l) {
    function iter(l, s) {
        return is_null(l) ?
            s + ")" :
            iter(tail(l), s + ", " + stringfy(head(l)));
    }
    return is_null(l) ?
        display("list()") :
        display(iter(tail(l), "list(" + stringfy(head(l))));
}
function display(x) {
    return console.log(x);
}
function is_null(x) {
    return x === null;
}
function map(f, items) {
    return is_null(items) ?
        null :
        pair(
            f(head(items)),
            map(f, tail(items))
        );
}
function square(x) {
    return x * x;
}

function square_list1(items) {
    return is_null(items) ?
        null :
        pair(
            square(head(items)),
            square_list1(tail(items))
        );
}
function square_list2(items) {
    return map(square, items);
}
const nums = list(1, 2, 3, 4);

print_list(square_list1(nums));
print_list(square_list2(nums));

入出力結果(Terminal, Zsh)

% node answer2.21.js
list(1, 4, 9, 16)
list(1, 4, 9, 16)
%