計算機科学のブログ

Building Abstractions with Data - Introduction to Data Abstraction - Abstraction Barriers - rectangle, point, width, height, perimeter, area

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.3の解答を求めてみる。

コード

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 make_rect(bottom_left, top_right) {
    return pair(bottom_left, top_right);
}
function bottom_left(rect) {
    return head(rect);
}
function top_right(rect) {
    return tail(rect);
}
function width_rect(rect) {
    const bl = bottom_left(rect);
    const tr = top_right(rect);
    return x_point(tr) - x_point(bl);
}
function height_rect(rect) {
    const bl = bottom_left(rect);
    const tr = top_right(rect);
    return y_point(tr) - y_point(bl);
}
function perimeter_rect(rect) {
    return 2 * (width_rect(rect) + height_rect(rect));
}
function area_rect(rect) {
    return width_rect(rect) * height_rect(rect);
}

const rect = make_rect(make_point(-1, 2), make_point(3, 4));
display(rect);
display(perimeter_rect(rect));
display(area_rect(rect));

function make_rect1(width, height) {
    return pair(width, height);
}
function width_rect1(rect) {
    return head(rect);
}
function height_rect1(rect) {
    return tail(rect);
}
function perimeter_rect1(rect) {
    return 2 * (width_rect1(rect) + height_rect1(rect));
}
function area_rect1(rect) {
    return width_rect1(rect) * height_rect1(rect);
}
const rect1 = make_rect(2, 3);
display(rect1);
display(perimeter_rect1(rect1));
display(area_rect1(rect1));

入出力結果(Terminal, Zsh)

% node answer2.3.js 
[ [ -1, 2 ], [ 3, 4 ] ]
12
8
[ 2, 3 ]
10
6
%