Building Abstractions with Data - Hierarchical Data and the Closure Property - Representing Sequences - List operations - 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.1(Representing Sequences)、List operations、Exercise 2.18の解答を求めてみる。
コード
function display(x) {
return console.log(x);
}
function stringfy(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 print_list(l) {
function iter(l, s) {
return is_null(l) ?
s + ")" :
iter(tail(l), s + ", " + stringfy(head(l)));
}
return is_null(l) ?
display("list()") :
display(iter(tail(l), "list(" + stringfy(head(l))));
}
function is_null(x) {
return x === null;
}
function last_pair(l) {
const t = tail(l);
return is_null(t) ?
l :
last_pair(t);
}
function reverse(l) {
function iter(l, r) {
return is_null(l) ?
r :
iter(tail(l), pair(head(l), r));
}
return iter(l, null);
}
print_list(
reverse(
list(1, 4, 9, 16, 25)
)
);
print_list(
reverse(null)
);
print_list(
reverse(list(1))
);
入出力結果(Terminal, Zsh)
% node answer2.18.js
list(25, 16, 9, 4, 1)
list()
list(1)
%