計算機科学のブログ

Building Abstractions with Data - Introduction to Data Abstraction - Extended Exercise: Interval Arithmetic - interval, mid point, ratio of width, 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.4(Extended Exercise: Interval Arithmetic)、Exercise 2.12解答を求めてみる。

コード

function math_abs(x) {
    return Math.abs(x);
}
function display(x) {
    return console.log(x);
}
function pair(x, y) {
    return [x, y];
}
function head(z) {
    return z[0];
}
function tail(z) {
    return z[1];
}
function make_interval(x, y) {
    return pair(x, y);
}
function lower_bound(i) {
    return head(i);
}
function upper_bound(i) {
    return tail(i);
}
function make_center_percent(c, p) {
    const w = math_abs(c) * p / 100;
    return make_interval(c - w, c + w);
}
function center(i) {
    return (lower_bound(i) + upper_bound(i)) / 2;
}
function percent(i) {
    const u = upper_bound(i);
    const m = center(i);
    return (u - m) / m * 100;
}
const i1 = make_center_percent(2, 10);
const i2 = make_center_percent(-2, 10);

display(i1);
display(percent(i1));
display(i2);
display(percent(i2));

入出力結果(Terminal, Zsh)

% node answer2.12.js 
[ 1.8, 2.2 ]
10.000000000000009
[ -2.2, -1.8 ]
-9.999999999999998
%