計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Representing Sequences - List operations - higher-order functions, currying

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)、List operations、Exercise 2.20の解答を求めてみる。

コード

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 plus_curried(x) {
    return y => x + y;
}
function brooks(f, l) {
    function iter(f, l) {
        return is_null(l) ?
            f :
            iter(f(head(l)), tail(l));
    }
    return iter(f, l);
}

display(brooks(plus_curried, list(3, 4)));

function brooks_curried(l) {
    return brooks(head(l), tail(l));
}

display(brooks_curried(list(plus_curried, 3, 4)));

display(
    brooks_curried(
        list(
            brooks_curried,
            list(plus_curried, 3, 4)
        )
    ) ===
    7
);

display(
    brooks_curried(
        list(
            brooks_curried,
            list(
                brooks_curried,
                list(plus_curried, 3, 4)
            )
        )
    ) ===
    7
);

入出力結果(Terminal, Zsh)

% node answer2.20.js
7
7
true
true
%