Building Abstractions with Data - Introduction to Data Abstraction - Extended Exercise: Interval Arithmetic - abstraction, constructor, selectors, upper bound, lower bound, subtraction
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.1(Introduction to Data Abstraction)、2.1.4(Extended Exercise: Interval Arithmetic)、Exercise 2.7、2.8の解答を求めてみる。
コード
function pair(x, y) {
return [x, y];
}
function head(z) {
return z[0];
}
function tail(z) {
return z[1];
}
function make_interval(x, y) {
return pair(x, y);
}
function upper_bound(interval) {
return tail(interval);
}
function lower_bound(interval) {
return head(interval);
}
function sub_interval(x, y) {
return make_interval(
lower_bound(x) - upper_bound(y),
upper_bound(x) - lower_bound(y)
);
}
const interval1 = make_interval(1, 2);
const interval2 = make_interval(3, 5);
const interval3 = sub_interval(interval1, interval2);
const interval4 = sub_interval(interval2, interval1);
console.log(interval1);
console.log(interval2);
console.log(interval3);
console.log(interval4);
入出力結果(Terminal, Zsh)
% node answer2.7.js
[ 1, 2 ]
[ 3, 5 ]
[ -4, -1 ]
[ 1, 4 ]
%