Building Abstractions with Data - Introduction to Data Abstraction - Example: Arithmetic Operations for Rational Numbers - numerator, demoninator, sign
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.1(Example: Arithmetic Operations for Rational Numbers)、Exercise 2.1の解答を求めてみる。
コード
function math_abs(x) {
return Math.abs(x);
}
function stringfy(x) {
return x.toString();
}
function display(x) {
return console.log(x);
}
function pair(x, y) {
return [x, y];
}
function head(p) {
return p[0];
}
function tail(p) {
return p[1];
}
function gcd(a, b) {
const r = a % b;
return r === 0 ?
b :
gcd(b, r);
}
function make_rat(n, d) {
const g = gcd(n, d);
const a = n / g;
const b = d / g;
return b >= 0 ?
pair(a, b) :
a >= 0 ?
pair(-1 * a, math_abs(b)) :
pair(math_abs(a), math_abs(b));
}
function numer(x) {
return head(x);
}
function denom(x) {
return tail(x);
}
function print_rat(x) {
return display(stringfy(numer(x)) + " / " + stringfy(denom(x)));
}
print_rat(make_rat(16, 20));
print_rat(make_rat(-16, 20));
print_rat(make_rat(16, -20));
print_rat(make_rat(-16, -20));
入出力結果(Terminal, Zsh)
% node answer2.1.js
4 / 5
-4 / 5
-4 / 5
4 / 5
%