Building Abstractions with Data - Symbolic Data - Strings - list, tail, member
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.1(Strings)、Exercise 2.53の解答を求めてみる。
コード
function stringfy(x) {
if (x === undefined) {
return 'undefined';
}
if (is_null(x)) {
return "null";
}
if (is_pair(x)) {
return "[" + stringfy(head(x)) + ", " + stringfy(tail(x)) + "]";
}
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 is_null(x) {
return x === null;
}
function list(...args) {
return args.length === 0 ?
null :
pair(args[0], list(...args.slice(1)));
}
function member(item, x) {
return is_null(x) ?
null :
item === head(x) ?
x :
member(item, tail(x));
}
// ["1", ["b", ["c", null]]]
display(list("1", "b", "c"))
// [["george", null], null]
display(list(list("george")));
// [["y1", ["y2", null]], null]
display(tail(list(list("x1", "x2"), list("y1", "y2"))));
// ["x2", null]
display(tail(head(list(list("x1", "x2"), list("y1", "y2")))));
// null
display(member("red", list("blue", "shoes", "yellow", "socks")));
// ["red", ["shoes", ["blue", ["socks", null]]]]
display(member("red", list("red", "shoes", "blue", "socks")));