Building Abstractions with Data - Hierarchical Data and the Closure Property - Hierarchical Structures - list, combinations of heads and tails
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.25の解答を求めてみる。
コード
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;
}
display(
head(tail(head(tail(tail(
list(1, 3, list(5, 7), 9)
)))))
);
display(
head(head(
list(list(7))
))
);
display(
head(tail(head(tail(head(tail(head(tail(head(tail(head(tail(
list(1, list(2, list(3, list(4, list(5, list(6, 7))))))
))))))))))))
);
入出力結果(Terminal, Zsh)
% node answer2.25.js
7
7
7
%