計算機科学のブログ

Building Abstractions with Data - Hierarchical Data and the Closure Property - Example: A Picture Language - Frames - constructors, selectors, list, pair

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)、Frames、Exercise 2.47の解答を求めてみる。

コード

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 list(...args) {
    return args.length === 0 ?
        null :
        pair(args[0], list(...args.slice(1)));
}
function display(x) {
    return console.log(stringfy(x));
}
function make_frame1(origin, edge1, edge2) {
    return list(origin, edge1, edge2);
}
function origin1(frame) {
    return head(frame);
}
function edge11(frame) {
    return head(tail(frame));
}
function edge12(frame) {
    return head(tail(tail(frame)));
}
const frame1 = make_frame1("origin", "edge1", "edge2");
display(origin1(frame1));
display(edge11(frame1));
display(edge12(frame1));
function make_frame2(origin, edge1, edge2) {
    return pair(origin, pair(edge1, edge2));
}
function origin2(frame) {
    return head(frame);
}
function edge21(frame) {
    return head(tail(frame));
}
function edge22(frame) {
    return tail(tail(frame));
}
const frame2 = make_frame2("origin", "edge1", "edge2");
display(origin2(frame2));
display(edge21(frame2));
display(edge22(frame2));

入出力結果(Terminal, Zsh)

% node answer2.47.js
origin
edge1
edge2
origin
edge1
edge2
%