計算機科学のブログ

Building Abstractions with Data - Symbolic Data - Example: Symbolic Differentiation - Representing algebraic expressions - exponent

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.56の解答を求めてみる。

コード

function stringfy(x) {
    if (is_null(x)) {
        return "null";
    }
    if (is_pair(x)) {
        return "[" + stringfy(head(x)) + ", " + stringfy(tail(x)) + "]";
    }
    return x.toString();
}
function display(x) {
    return console.log(stringfy(x));
}
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 is_number(x) {
    return typeof x === "number";
}
function number_equal(x, y) {
    return is_number(x) && x === y;
}
function is_exp(exp) {
    return is_pair(exp) &&
        head(exp) === '**';
}
function base(exp) {
    return head(tail(exp));
}
function exponent(exp) {
    return head(tail(tail(exp)));
}
function make_exp(b, e) {
    return number_equal(e, 0)
        ? 1
        : number_equal(e, 1)
            ? b
            : list("**", b, e);
}
const exp = make_exp(2, 3);
const exp0 = make_exp(2, 0);
const exp1 = make_exp(2, 1);

function deriv(exp, variable) {
    return is_exp(exp) ?
        make_product(
            exponent(exp),
            make_product(
                make_exp(
                    base(exp),
                    make_sum(
                        exponent(exp),
                        -1
                    )
                ),
                deriv(
                    base(exp),
                    variable
                )
            )
        ) :
        error(exp, "unknown expression type -- deriv");
}
function iter(exps) {
    function f(exps) {
        display("**********");
        if (!is_null(exps)) {
            const exp = head(exps);
            display(exp);
            if (is_exp(exp)) {
                display(is_exp(exp));
                display(base(exp));
                display(exponent(exp));
            }
            return iter(tail(exps));
        }
    }
    return f(exps);
}
iter(list(exp, exp0, exp1));

入出力結果(Terminal, Zsh)

% node answer2.56.js
**********
[**, [2, [3, null]]]
true
2
3
**********
1
**********
2
**********
%