計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Example: A Picture Language - Painters - directed line segment

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.4(Example: A Picture Language)、Painters、Exercise 2.48の解答を求めてみる。

コード

function stringfy(x) {
    if (x === undefined) {
        return 'undefined';
    }
    if (is_null(x)) {
        return "null";
    }
    if (is_pair(x)) {
        return "[" + stringfy(head(x)) + ", " + stringfy(tail(x)) + "]";
    }
    return x.toString();
}
function pair(x, y) {
    return [x, y];
}
function head(z) {
    return z[0];
}
function tail(z) {
    return z[1];
}
function is_pair(x) {
    return Array.isArray(x);
}
function is_null(x) {
    return x === null;
}
function display(x) {
    return console.log(stringfy(x));
}
function make_vect(x, y) {
    return pair(x, y);
}
function xcor_vect(v) {
    return head(v);
}
function ycor_vect(v) {
    return tail(v);
}
function make_segment(start_vect, end_vect) {
    return pair(start_vect, end_vect);
}
function start_segment(segment) {
    return head(segment);
}
function end_segument(segment) {
    return tail(segment);
}
const v1 = make_vect(1, 2);
const v2 = make_vect(3, 5);
const segment = make_segment(v1, v2);
display(segment);
display(start_segment(segment));
display(end_segument(segment));

入出力結果(Terminal, Zsh)

% node answer2.48.js
[[1, 2], [3, 5]]
[1, 2]
[3, 5]
%