Building Abstractions with Data - Hierarchical Data and the Closure Property - Hierarchical Structures - list, append, pair
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.26の解答を求めてみる。
コード
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 list(...args) {
return args.length === 0 ?
null :
pair(args[0], list(...args.slice(1)));
}
function display(x) {
return console.log(stringfy(x));
}
function is_pair(x) {
return Array.isArray(x);
}
function is_null(x) {
return x === null;
}
function append(list1, list2) {
return is_null(list1) ?
list2 :
pair(head(list1), append(tail(list1), list2));
}
const x = list(1, 2, 3);
const y = list(4, 5, 6);
display('[1, [2, [3, [4, [5, [6, null]]]]]]');
display(
append(x, y)
);
display('[[1, [2, [3, null]]], [4, [5, [6, null]]]]');
display(
pair(x, y)
);
display('[[1, [2, [3, null]]], [[4, [5, [6, null]]], null]]');
display(
list(x, y)
);
入出力結果(Terminal, Zsh)
% node answer2.26.js
[1, [2, [3, [4, [5, [6, null]]]]]]
[1, [2, [3, [4, [5, [6, null]]]]]]
[[1, [2, [3, null]]], [4, [5, [6, null]]]]
[[1, [2, [3, null]]], [4, [5, [6, null]]]]
[[1, [2, [3, null]]], [[4, [5, [6, null]]], null]]
[[1, [2, [3, null]]], [[4, [5, [6, null]]], null]]
%