Building Abstractions with Data - Hierarchical Data and the Closure Property - Representing Sequences - List operations - last element
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.17の解答を求めてみる。
コード
function display(x) {
return console.log(x);
}
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 is_null(x) {
return x === null;
}
function last_pair(l) {
const t = tail(l);
return is_null(t) ?
l :
last_pair(t);
}
display(last_pair(list(23, 72, 149, 34)));
入出力結果(Terminal, Zsh)
% node answer2.17.js
[ 34, null ]
%