Building Abstractions with Data - Introduction to Data Abstraction - Abstraction Barriers - segment, midpoint, constructor, selector
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.2(Abstraction Barriers)、Exercise 2.2の解答を求めてみる。
コード
function display(x) {
return console.log(x);
}
function stringfy(x) {
return x.toString();
}
function average(x, y) {
return (x + y) / 2;
}
function pair(x, y) {
return [x, y]
}
function head(pair) {
return pair[0];
}
function tail(pair) {
return pair[1];
}
function make_segment(start_segment, end_segment) {
return pair(start_segment, end_segment);
}
function start_segment(segment) {
return head(segment);
}
function end_segment(segment) {
return tail(segment);
}
function make_point(x, y) {
return pair(x, y);
}
function x_point(point) {
return head(point);
}
function y_point(point) {
return tail(point);
}
function print_point(point) {
return display(
"(" + stringfy(x_point(point)) + ", " +
stringfy(y_point(point)) + ")"
);
}
function midpoint_segment(segment) {
const start_seg = start_segment(segment);
const end_seg = end_segment(segment);
return make_point(
average(
x_point(start_seg),
x_point(end_seg)
),
average(
y_point(start_seg),
y_point(end_seg)
)
);
}
const start_point = make_point(-1, 2);
const end_point = make_point(1, -2);
const segment = make_segment(start_point, end_point);
const mid_point = midpoint_segment(segment);
print_point(mid_point);
print_point(
midpoint_segment(
make_segment(
make_point(2, 3),
make_point(10, -1)
)
)
);
入出力結果(Terminal, Zsh)
% node answer2.2.js
(0, 0)
(6, 1)
%