計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Representing Sequences - Mapping over lists - for_each function

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

コード

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 display(x) {
    return console.log(x);
}
function is_null(x) {
    return x === null;
}
function for_each(f, items) {
    function iter(items) {
        if (!is_null(items)) {
            f(head(items));
            iter(tail(items));
        }
    }
    return iter(items);
}
display(
    for_each(
        x => display(x),
        list(57, 321, 88)
    )
);

入出力結果(Terminal, Zsh)

% node answer2.23.js
57
321
88
undefined
%