Building Abstractions with Data - Symbolic Data - Example: Symbolic Differentiation - Representing algebraic expressions - infix operators, abstract data, predicates, selectors, constructors
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.3(Symbolic Data)、2.3.2(Example: Symbolic Differentiation)、Representing algebraic expressions、Exercise 2.58の解答を求めてみる。
コード
function stringfy(x) {
if (is_null(x)) {
return "null";
}
if (is_pair(x)) {
return "[" + stringfy(head(x)) + ", " + stringfy(tail(x)) + "]";
}
if (x === undefined) {
return "undefined";
}
return x.toString();
}
function display(x) {
return console.log(stringfy(x));
}
function error(x) {
return console.error(x);
}
function is_number(x) {
return typeof x === "number";
}
function is_string(x) {
return typeof x === "string";
}
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 list(...args) {
return args.length === 0 ?
null :
pair(args[0], list(...args.slice(1)));
}
function is_null(x) {
return x === null;
}
function number_equal(exp, num) {
return is_number(exp) && exp === num;
}
function is_variable(x) {
return is_string(x);
}
function is_same_variable(v1, v2) {
return is_variable(v1) && is_variable(v2) && v1 === v2;
}
function make_sum(a1, a2) {
return number_equal(a1, 0)
? a2
: number_equal(0, a2)
? a1
: is_number(a1) && is_number(a2)
? a1 + a2
: list(a1, "+", a2);
}
function addend(s) {
return head(s);
}
function augend(s) {
return head(tail(tail(s)));
}
function is_sum(x) {
return is_pair(x) && head(tail(x)) === "+";
}
function make_product(m1, m2) {
return number_equal(m1, 0) || number_equal(0, m2)
? 0
: number_equal(m1, 1)
? m2
: number_equal(1, m2)
? m1
: is_number(m1) && is_number(m2)
? m1 * m2
: list(m1, "*", m2);
}
function multiplier(s) {
return head(s);
}
function multiplicand(s) {
return head(tail(tail(s)))
}
function is_product(x) {
return is_pair(x) && head(tail(x)) === "*";
}
function deriv(exp, variable) {
return is_number(exp)
? 0
: is_variable(exp)
? is_same_variable(exp, variable)
? 1
: 0
: is_sum(exp)
? make_sum(
deriv(addend(exp), variable),
deriv(augend(exp), variable)
)
: is_product(exp)
? make_sum(
make_product(
multiplier(exp),
deriv(
multiplicand(exp),
variable
)
),
make_product(
deriv(
multiplier(exp),
variable
),
multiplicand(exp)
)
)
: error(exp, "unknown expression type -- deriv");
}
// x + (3 * (x + (y + 2)))
const exp = list("x", "+",
list(3, "*",
list("x", "+",
list("y", "+", 2))));
display(exp);
// 1 + 3 = 4
display(deriv(exp, "x"));
入出力結果(Terminal, Zsh)
% node answer2.58.js
[x, [+, [[3, [*, [[x, [+, [[y, [+, [2, null]]], null]]], null]]], null]]]
4
%