Building Abstractions with Data - Hierarchical Data and the Closure Property - Hierarchical Structures - list, deep reverse 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.2(Hierarchical Structures)、Exercise 2.27の解答を求めてみる。
コード
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 is_list(x) {
return is_null(x) ||
(is_pair(x) && is_list(tail(x)));
}
function display(x) {
return console.log(stringfy(x));
}
function append(list1, list2) {
return is_null(list1) ?
list2 :
pair(head(list1), append(tail(list1), list2));
}
function reverse(x) {
function iter(y, result) {
return is_null(y) ?
result :
iter(tail(y), pair(head(y), result));
}
return iter(x, null);
}
function deep_reverse(x) {
function iter(y, result) {
if (is_null(y)) {
return result;
}
const v = head(y);
return iter(
tail(y),
pair(
is_pair(v) ?
deep_reverse(v) :
v,
result)
);
}
return iter(x, null);
}
const x = list(list(1, 2), list(3, 4));
display(x);
display(reverse(x));
display(deep_reverse(x));
入出力結果(Terminal, Zsh)
% node answer2.27.js
[[1, [2, null]], [[3, [4, null]], null]]
[[3, [4, null]], [[1, [2, null]], null]]
[[4, [3, null]], [[2, [1, null]], null]]
%