/
builtin_arithmetic.go
343 lines (320 loc) · 8.68 KB
/
builtin_arithmetic.go
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package expreduce
import "math/big"
func ExArrayContainsFloat(a []Ex) bool {
res := false
for _, e := range a {
_, isfloat := e.(*Flt)
res = res || isfloat
}
return res
}
func RationalAssertion(num Ex, den Ex) (r *Rational, isR bool) {
numInt, numIsInt := num.(*Integer)
denPow, denIsPow := HeadAssertion(den, "System`Power")
if !numIsInt || !denIsPow {
return nil, false
}
powInt, powIsInt := denPow.Parts[2].(*Integer)
if !powIsInt {
return nil, false
}
if powInt.Val.Cmp(big.NewInt(-1)) != 0 {
return nil, false
}
denInt, denIsInt := denPow.Parts[1].(*Integer)
if !denIsInt {
return nil, false
}
return NewRational(numInt.Val, denInt.Val), true
}
type FoldFn int
const (
FoldFnAdd FoldFn = iota
FoldFnMul
)
func typedRealPart(fn FoldFn, i *Integer, r *Rational, f *Flt) Ex {
if f != nil {
toReturn := f
if r != nil {
if fn == FoldFnAdd {
toReturn.AddR(r)
} else if fn == FoldFnMul {
toReturn.MulR(r)
}
}
if i != nil {
if fn == FoldFnAdd {
toReturn.AddI(i)
} else if fn == FoldFnMul {
toReturn.MulI(i)
}
}
return toReturn
}
if r != nil {
toReturn := r
if i != nil {
if fn == FoldFnAdd {
toReturn.AddI(i)
} else if fn == FoldFnMul {
toReturn.MulI(i)
}
}
return toReturn
}
if i != nil {
return i
}
return nil
}
func computeRealPart(fn FoldFn, e *Expression) (Ex, int) {
var foldedInt *Integer
var foldedRat *Rational
var foldedFlt *Flt
for i := 1; i < len(e.Parts); i++ {
// TODO: implement short circuiting if we encounter a zero while
// multiplying.
asInt, isInt := e.Parts[i].(*Integer)
if isInt {
if foldedInt == nil {
// Try deepcopy if problems. I think this does not cause
// problems now because we will only modify the value if we end
// up creating an entirely new expression.
foldedInt = asInt.DeepCopy().(*Integer)
continue
}
if fn == FoldFnAdd {
foldedInt.AddI(asInt)
} else if fn == FoldFnMul {
foldedInt.MulI(asInt)
}
continue
}
asRat, isRat := e.Parts[i].(*Rational)
if isRat {
if foldedRat == nil {
foldedRat = asRat.DeepCopy().(*Rational)
continue
}
if fn == FoldFnAdd {
foldedRat.AddR(asRat)
} else if fn == FoldFnMul {
foldedRat.MulR(asRat)
}
continue
}
asFlt, isFlt := e.Parts[i].(*Flt)
if isFlt {
if foldedFlt == nil {
foldedFlt = asFlt.DeepCopy().(*Flt)
continue
}
if fn == FoldFnAdd {
foldedFlt.AddF(asFlt)
} else if fn == FoldFnMul {
foldedFlt.MulF(asFlt)
}
continue
}
return typedRealPart(fn, foldedInt, foldedRat, foldedFlt), i
}
return typedRealPart(fn, foldedInt, foldedRat, foldedFlt), -1
}
func splitTerm(e Ex) (Ex, Ex, bool) {
asSym, isSym := e.(*Symbol)
if isSym {
return &Integer{big.NewInt(1)}, NewExpression([]Ex{
&Symbol{"System`Times"},
asSym,
}), true
}
asTimes, isTimes := HeadAssertion(e, "System`Times")
if isTimes {
if len(asTimes.Parts) < 2 {
return nil, nil, false
}
if numberQ(asTimes.Parts[1]) {
if len(asTimes.Parts) > 2 {
return asTimes.Parts[1], NewExpression(append([]Ex{&Symbol{"System`Times"}}, asTimes.Parts[2:]...)), true
}
} else {
return &Integer{big.NewInt(1)}, NewExpression(append([]Ex{&Symbol{"System`Times"}}, asTimes.Parts[1:]...)), true
}
}
asExpr, isExpr := e.(*Expression)
if isExpr {
return &Integer{big.NewInt(1)}, NewExpression([]Ex{
&Symbol{"System`Times"},
asExpr,
}), true
}
return nil, nil, false
}
func collectedToTerm(coeffs []Ex, vars Ex, fullPart Ex) Ex {
// Preserve the original expression if there is no need to change it.
// We can keep all the cached values like the hash.
if len(coeffs) == 1 {
return fullPart
}
finalC, _ := computeRealPart(FoldFnAdd, NewExpression(append([]Ex{
&Symbol{"System`Plus"}}, coeffs...)))
toAdd := NewExpression([]Ex{&Symbol{"System`Times"}})
cAsInt, cIsInt := finalC.(*Integer)
if !(cIsInt && cAsInt.Val.Cmp(big.NewInt(1)) == 0) {
toAdd.Parts = append(toAdd.Parts, finalC)
}
vAsExpr, vIsExpr := HeadAssertion(vars, "System`Times")
if vIsExpr && len(vAsExpr.Parts) == 2 {
vars = vAsExpr.Parts[1]
}
toAdd.Parts = append(toAdd.Parts, vars)
if len(toAdd.Parts) == 2 {
return toAdd.Parts[1]
}
return toAdd
}
func collectTerms(e *Expression) *Expression {
collected := NewExpression([]Ex{&Symbol{"System`Plus"}})
var lastVars Ex
var lastFullPart Ex
lastCoeffs := []Ex{}
for _, part := range e.Parts[1:] {
coeff, vars, isTerm := splitTerm(part)
if isTerm {
if lastVars == nil {
lastCoeffs = []Ex{coeff}
lastVars = vars
lastFullPart = part
} else {
if hashEx(vars) == hashEx(lastVars) {
lastCoeffs = append(lastCoeffs, coeff)
} else {
collected.Parts = append(collected.Parts, collectedToTerm(lastCoeffs, lastVars, lastFullPart))
lastCoeffs = []Ex{coeff}
lastVars = vars
lastFullPart = part
}
}
} else {
collected.Parts = append(collected.Parts, part)
}
}
if lastVars != nil {
collected.Parts = append(collected.Parts, collectedToTerm(lastCoeffs, lastVars, lastFullPart))
}
return collected
}
func getArithmeticDefinitions() (defs []Definition) {
defs = append(defs, Definition{
Name: "Plus",
Default: "0",
toString: func(this *Expression, form string, context *String, contextPath *Expression) (bool, string) {
return ToStringInfix(this.Parts[1:], " + ", form, context, contextPath)
},
legacyEvalFn: func(this *Expression, es *EvalState) Ex {
// Calls without argument receive identity values
if len(this.Parts) == 1 {
return &Integer{big.NewInt(0)}
}
res := this
realPart, symStart := computeRealPart(FoldFnAdd, this)
if realPart != nil {
if symStart == -1 {
return realPart
}
res = NewExpression([]Ex{&Symbol{"System`Plus"}})
rAsInt, rIsInt := realPart.(*Integer)
if !(rIsInt && rAsInt.Val.Cmp(big.NewInt(0)) == 0) {
res.Parts = append(res.Parts, realPart)
}
res.Parts = append(res.Parts, this.Parts[symStart:]...)
}
collected := collectTerms(res)
if hashEx(collected) != hashEx(res) {
res = collected
}
// If one expression remains, replace this Plus with the expression
if len(res.Parts) == 2 {
return res.Parts[1]
}
return res
},
})
defs = append(defs, Definition{
Name: "Sum",
legacyEvalFn: func(this *Expression, es *EvalState) Ex {
return this.evalIterationFunc(es, &Integer{big.NewInt(0)}, "System`Plus")
},
})
defs = append(defs, Definition{
Name: "Times",
Default: "1",
toString: func(this *Expression, form string, context *String, contextPath *Expression) (bool, string) {
return ToStringInfix(this.Parts[1:], " * ", form, context, contextPath)
},
legacyEvalFn: func(this *Expression, es *EvalState) Ex {
// Calls without argument receive identity values
if len(this.Parts) == 1 {
return &Integer{big.NewInt(1)}
}
res := this
realPart, symStart := computeRealPart(FoldFnMul, this)
if realPart != nil {
if symStart == -1 {
return realPart
}
res = NewExpression([]Ex{&Symbol{"System`Times"}})
rAsInt, rIsInt := realPart.(*Integer)
if rIsInt && rAsInt.Val.Cmp(big.NewInt(0)) == 0 {
containsInfinity := MemberQ(this.Parts[symStart:], NewExpression([]Ex{
&Symbol{"System`Alternatives"},
&Symbol{"System`Infinity"},
&Symbol{"System`ComplexInfinity"},
}), es)
if containsInfinity {
return &Symbol{"System`Indeterminate"}
}
return &Integer{big.NewInt(0)}
}
if !(rIsInt && rAsInt.Val.Cmp(big.NewInt(1)) == 0) {
res.Parts = append(res.Parts, realPart)
}
res.Parts = append(res.Parts, this.Parts[symStart:]...)
}
// If one expression remains, replace this Times with the expression
if len(res.Parts) == 2 {
return res.Parts[1]
}
// Automatically Expand negations (*-1), not (*-1.) of a Plus expression
// Perhaps better implemented as a rule.
if len(res.Parts) == 3 {
leftint, leftintok := res.Parts[1].(*Integer)
rightplus, rightplusok := HeadAssertion(res.Parts[2], "System`Plus")
if leftintok && rightplusok {
if leftint.Val.Cmp(big.NewInt(-1)) == 0 {
toreturn := NewExpression([]Ex{&Symbol{"System`Plus"}})
addends := rightplus.Parts[1:len(rightplus.Parts)]
for i := range addends {
toAppend := NewExpression([]Ex{
&Symbol{"System`Times"},
addends[i],
&Integer{big.NewInt(-1)},
})
toreturn.Parts = append(toreturn.Parts, toAppend)
}
return toreturn.Eval(es)
}
}
}
return res
},
})
defs = append(defs, Definition{
Name: "Product",
legacyEvalFn: func(this *Expression, es *EvalState) Ex {
return this.evalIterationFunc(es, &Integer{big.NewInt(1)}, "System`Times")
},
})
defs = append(defs, Definition{Name: "Abs"})
return
}