Building Abstractions with Data - Symbolic Data - Example: Representing Sets - Sets as ordered lists - adjoin set
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.3(Symbolic Data)、2.3.3(Example: Representing Sets)、Sets as ordered lists、Exercise 2.61の解答を求めてみる。
コード
function stringfy(x) {
if (is_null(x)) {
return "null";
}
if (is_pair(x)) {
return "[" + stringfy(head(x)) + ", " + stringfy(tail(x)) + "]";
}
if (x === undefined) {
return "undefined";
}
return x.toString();
}
function display(x) {
return console.log(stringfy(x));
}
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 list(...args) {
return args.length === 0 ?
null :
pair(args[0], list(...args.slice(1)));
}
function is_null(x) {
return x === null;
}
function adjoin_set(x, set) {
if (is_null(set)) {
return pair(x, set);
}
const y = head(set);
return x < y
? pair(x, set)
: x === y
? set
: pair(y, adjoin_set(x, tail(set)));
}
const set = list(1, 3, 6, 10);
function iter(n) {
function f(m) {
if (m <= n) {
display(m);
display(adjoin_set(m, set));
f(m + 1);
}
}
f(0);
}
display(set);
iter(11);
入出力結果(Terminal, Zsh)
% node answer2.61.js
[1, [3, [6, [10, null]]]]
0
[0, [1, [3, [6, [10, null]]]]]
1
[1, [3, [6, [10, null]]]]
2
[1, [2, [3, [6, [10, null]]]]]
3
[1, [3, [6, [10, null]]]]
4
[1, [3, [4, [6, [10, null]]]]]
5
[1, [3, [5, [6, [10, null]]]]]
6
[1, [3, [6, [10, null]]]]
7
[1, [3, [6, [7, [10, null]]]]]
8
[1, [3, [6, [8, [10, null]]]]]
9
[1, [3, [6, [9, [10, null]]]]]
10
[1, [3, [6, [10, null]]]]
11
[1, [3, [6, [10, [11, null]]]]]
%