計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Sequences as Conventional Interfaces - Sequence Operations - accumulate_n, a sequence of sequences

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.3(Sequences as Conventional Interfaces)、Sequence Operations、Exercise 2.36の解答を求めてみる。

コード

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 display(x) {
    return console.log(stringfy(x));
}
function accumulate(op, initial, sequence) {
    return is_null(sequence) ?
        initial :
        op(
            head(sequence),
            accumulate(op, initial, tail(sequence))
        );
}
function map(f, sequence) {
    return accumulate(
        (x, y) => pair(f(x), y),
        null,
        sequence
    );
}
function accumulate_n(op, init, seqs) {
    return is_null(head(seqs)) ?
        null :
        pair(
            accumulate(
                op,
                init,
                map(
                    head,
                    seqs
                )
            ),
            accumulate_n(
                op,
                init,
                map(
                    tail,
                    seqs
                )
            )
        );
}
function plus(x, y) {
    return x + y;
}
const s = list(
    list(1, 2, 3),
    list(4, 5, 6),
    list(7, 8, 9),
    list(10, 11, 12)
);
display(s);
display(
    accumulate_n(plus, 0, s)
);

入出力結果(Terminal, Zsh)

% node answer2.36.js
[[1, [2, [3, null]]], [[4, [5, [6, null]]], [[7, [8, [9, null]]], [[10, [11, [12, null]]], null]]]]
[22, [26, [30, null]]]
%