-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20thSept_SymbolicProcessing3
87 lines (72 loc) · 2.15 KB
/
20thSept_SymbolicProcessing3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function is_variable(x) {
return is_string(x);
}
function is_same_variable(v1, v2) {
return is_variable(v1) && is_variable(v2) && v1 === v2;
}
function is_sum(x) {
return is_pair(x) && head(x) === "+";
}
function is_product(x) {
return is_pair(x) && head(x) === "*";
}
function addend(s) {
return head(tail(s));
}
function augend(s) {
return head(tail(tail(s)));
}
function multiplier(s) {
return head(tail(s));
}
function multiplicand(s) {
return head(tail(tail(s)));
}
function number_equal(exp, num) {
return is_number(exp) && exp === num;
}
// make_sum and make_product by expression simplification
function make_sum(a1, a2) {
return number_equal(a1, 0)
? a2
: number_equal(a2, 0)
? a1
: is_number(a1) && is_number(a2)
? a1 + a2
: list("+", a1, a2);
}
function make_product(m1, m2) {
return number_equal(m1, 0) || number_equal(m2, 0)
? 0
: number_equal(m1, 1)
? m2
: number_equal(m2, 1)
? m1
: is_number(m1) && is_number(m2)
? m1 * m2
: list("*", m1, m2);
}
function deriv_symbolic(exp, variable) {
return is_number(exp)
? 0
: is_variable(exp)
? (is_same_variable(exp, variable)) ? 1 : 0
: is_sum(exp)
? make_sum(deriv_symbolic(addend(exp), variable),
deriv_symbolic(augend(exp), variable))
: is_product(exp)
? make_sum(make_product(multiplier(exp),
deriv_symbolic(multiplicand(exp),
variable)),
make_product(deriv_symbolic(multiplier(exp),
variable),
multiplicand(exp)))
: error(exp, "unknown expression type");
}
// my_exp represents x * x + x + 4
const my_exp = make_sum(make_product("x", "x"),
make_sum("x", 4));
display_list(deriv_symbolic(my_exp, "x"));
// should return make_sum(make_product("x", 2), 1)
// now returns an expression
// equivalent to 2 * x + 1