Building Abstractions with Data - Hierarchical Data and the Closure Property - Sequences as Conventional Interfaces - Sequence Operations - accumulation, fold right, fold left, associative law
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.38の解答を求めてみる。
コード
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 fold_right(op, initial, sequence) {
function iter(rest) {
return is_null(rest) ?
initial :
op(
head(rest),
iter(tail(rest))
);
}
return iter(sequence);
}
function fold_left(op, initial, sequence) {
function iter(result, rest) {
return is_null(rest) ?
result :
iter(
op(result, head(rest)),
tail(rest)
)
}
return iter(initial, sequence);
}
function divide(x, y) {
return x / y;
}
// 1/(2/(3/1))
// 1.5
display(fold_right(divide, 1, list(1, 2, 3)));
// ((1/1)/2)/3
// 0.16666…
display(fold_left(divide, 1, list(1, 2, 3)));
// list(1, list(2, list(3, null)))
// [1, [[2, [[3, [null, null]], null]], null]]
display(fold_right(list, null, list(1, 2, 3)));
// list(list(list(null, 1), 2), 3)
// [[[null, [1, null]], [2, null]], [3, null]]
display(fold_left(list, null, list(1, 2, 3)));
function plus(x, y) {
return x + y;
}
function times(x, y) {
return x * y;
}
display(fold_right(plus, 0, list(1, 2, 3, 4, 5)));
display(fold_left(plus, 0, list(1, 2, 3, 4, 5)));
display(fold_right(times, 1, list(1, 2, 3, 4, 5)));
display(fold_left(times, 1, list(1, 2, 3, 4, 5)));
入出力結果(Terminal, Zsh)
% node answer2.38.js
1.5
0.16666666666666666
[1, [[2, [[3, [null, null]], null]], null]]
[[[null, [1, null]], [2, null]], [3, null]]
15
15
120
120
%