Building Abstractions with Data - Hierarchical Data and the Closure Property - Example: A Picture Language - Frames - vector, constructor, selectors, addition, subtraction, scaling
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.46の解答を求めてみる。
コード
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 add_vect(v1, v2) {
return make_vect(
xcor_vect(v1) + xcor_vect(v2),
ycor_vect(v1) + ycor_vect(v2)
);
}
function sub_vect(v1, v2) {
return make_vect(
xcor_vect(v1) - xcor_vect(v2),
ycor_vect(v1) - ycor_vect(v2)
);
}
function scale_vect(s, v) {
return make_vect(
s * xcor_vect(v),
s * ycor_vect(v)
);
}
const v1 = make_vect(1, 5);
const v2 = make_vect(4, 2);
display(v1);
display(v2);
display(add_vect(v1, v2));
display(sub_vect(v1, v2));
display(scale_vect(10, v1));
display(scale_vect(10, v2));
入出力結果(Terminal, Zsh)
% node answer2.46.js
[1, 5]
[4, 2]
[5, 7]
[-3, 3]
[10, 50]
[40, 20]
%