Debian Codegraph @

texmf-dist/tex/lualatex/luacas/core/luacas-binaryoperation.lua

raw
1 --- @class BinaryOperation
2 --- Represents a binary operation with two inputs and one output.
3 --- Represents a generic function that takes zero or more expressions as inputs.
4 --- @field name string
5 --- @field operation function
6 --- @field expressions table<number, Expression>
7 BinaryOperation = {}
8 local __BinaryOperation = {}
9
10 ----------------------------
11 -- Instance functionality --
12 ----------------------------
13
14 --- Creates a new binary operation with the given operation.
15 --- @param operation function
16 --- @param expressions table<number, Expression>
17 --- @return BinaryOperation
18 function BinaryOperation:new(operation, expressions)
19 local o = {}
20 local __o = Copy(__ExpressionOperations)
21
22 if type(operation) ~= "function" then
23 error("Sent parameter of wrong type: operation must be a function")
24 end
25
26 if type(expressions) ~= "table" then
27 error("Sent parameter of wrong type: expressions must be an array")
28 end
29
30 o.name = BinaryOperation.DEFAULT_NAMES[operation]
31 o.operation = operation
32 o.expressions = Copy(expressions)
33
34 if BinaryOperation.COMMUTATIVITY[operation] then
35 function o:iscommutative()
36 return true
37 end
38 else
39 function o:iscommutative()
40 return false
41 end
42 end
43
44 if not o:iscommutative() and o.operation ~= BinaryOperation.SUB and #o.expressions ~= 2 then
45 error("Sent parameter of wrong type: noncommutative operations cannot have an arbitrary number of paramaters")
46 end
47
48 __o.__index = BinaryOperation
49 __o.__tostring = function(a)
50 local expressionnames = ''
51 for index, expression in ipairs(a.expressions) do
52 if index == 1 and not a.expressions[index + 1] then
53 expressionnames = expressionnames .. a.name .. ' '
54 end
55 if index > 1 then
56 expressionnames = expressionnames .. ' '
57 end
58 if expression:isatomic() and not (a.operation == BinaryOperation.POW and expression:type() == Rational) then
59 expressionnames = expressionnames .. tostring(expression)
60 else
61 expressionnames = expressionnames .. '(' .. tostring(expression) .. ')'
62 end
63 if a.expressions[index + 1] then
64 expressionnames = expressionnames .. ' ' .. a.name
65 end
66 end
67 return expressionnames
68 end
69 __o.__eq = function(a, b)
70 -- This shouldn't be needed, since __eq should only fire if both metamethods have the same function, but for some reason Lua always runs this anyway
71 if not a.operation or not b.operation then
72 return false
73 end
74 local loc = 1
75 while a.expressions[loc] or b.expressions[loc] do
76 if not a.expressions[loc] or not b.expressions[loc] or
77 (a.expressions[loc] ~= b.expressions[loc]) then
78 return false
79 end
80 loc = loc + 1
81 end
82 return a.operation == b.operation
83 end
84 o = setmetatable(o, __o)
85
86 return o
87 end
88
89 --- @return Expression
90 function BinaryOperation:evaluate()
91 local results = {}
92 local reducible = true
93 for index, expression in ipairs(self:subexpressions()) do
94 results[index] = expression:evaluate()
95 if not results[index]:isconstant() then
96 reducible = false
97 end
98 end
99 if not reducible then
100 return BinaryOperation(self.operation, results)
101 end
102
103 if not self.expressions[1] then
104 error("Execution error: cannot perform binary operation on zero expressions")
105 end
106
107 local result = results[1]
108 for index, expression in ipairs(results) do
109 if not (index == 1) then
110 result = self.operation(result, expression)
111 end
112 end
113 return result
114 end
115
116 --- @return Expression
117 function BinaryOperation:autosimplify()
118 local results = {}
119 for index, expression in ipairs(self:subexpressions()) do
120 results[index] = expression:autosimplify()
121 end
122 local simplified = BinaryOperation(self.operation, results)
123 if simplified.operation == BinaryOperation.POW then
124 return simplified:simplifypower()
125 end
126 if simplified.operation == BinaryOperation.MUL then
127 return simplified:simplifyproduct()
128 end
129 if simplified.operation == BinaryOperation.ADD then
130 return simplified:simplifysum()
131 end
132 if simplified.operation == BinaryOperation.DIV then
133 return simplified:simplifyquotient()
134 end
135 if simplified.operation == BinaryOperation.SUB then
136 return simplified:simplifydifference()
137 end
138 return simplified
139 end
140
141 --- @return table<number, Expression>
142 function BinaryOperation:subexpressions()
143 return self.expressions
144 end
145
146 --- @param subexpressions table<number, Expression>
147 --- @return BinaryOperation
148 function BinaryOperation:setsubexpressions(subexpressions)
149 return BinaryOperation(self.operation, subexpressions)
150 end
151
152 --- @return Expression
153 function BinaryOperation:expand()
154 local results = {}
155 for index, expression in ipairs(self:subexpressions()) do
156 results[index] = expression:expand()
157 end
158 local expanded = BinaryOperation(self.operation, results)
159 if expanded.operation == BinaryOperation.MUL then
160 local allsums = BinaryOperation(BinaryOperation.ADD, {Integer.one()})
161 for _, expression in ipairs(expanded.expressions) do
162 allsums = allsums:expand2(expression)
163 end
164 return allsums:autosimplify()
165 end
166 if expanded.operation == BinaryOperation.POW and expanded.expressions[2]:type() == Integer then
167 if expanded.expressions[1]:type() ~= BinaryOperation then
168 return expanded:autosimplify()
169 end
170 local exp = BinaryOperation.MULEXP({Integer.one()})
171 local pow = expanded.expressions[2]:asnumber()
172 for _ = 1, math.abs(pow) do
173 exp = exp:expand2(expanded.expressions[1])
174 if _ > 1 then
175 exp = exp:autosimplify()
176 end
177 end
178 if pow < 0 then
179 exp = exp^Integer(-1)
180 end
181 return exp
182 end
183 if expanded.operation == BinaryOperation.POW and expanded.expressions[2].operation == BinaryOperation.ADD then
184 local exp = {}
185 for i = 1, #expanded.expressions[2].expressions do
186 exp[#exp+1] = (expanded.expressions[1]^expanded.expressions[2].expressions[i]):autosimplify()
187 end
188 return BinaryOperation.MULEXP(exp)
189 end
190 return expanded:autosimplify()
191 end
192
193 --- Helper for expand - multiplies two addition expressions.
194 --- @return Expression
195 function BinaryOperation:expand2(other)
196 local result = {}
197 for _, expression in ipairs(self:subexpressions()) do
198 if other:type() == BinaryOperation and other.operation == BinaryOperation.ADD then
199 for _, expression2 in ipairs(other.expressions) do
200 result[#result+1] = expression * expression2
201 end
202 else
203 result[#result+1] = expression * other
204 end
205 end
206 return BinaryOperation(BinaryOperation.ADD, result)
207 end
208
209 --- @return Expression
210 function BinaryOperation:factor()
211 local results = {}
212
213 -- Recursively factors sub-expressions
214 for index, expression in ipairs(self:subexpressions()) do
215 results[index] = expression:factor()
216 end
217
218 -- Attempts to factor expressions as monovariate polynomials
219 local factoredsubs = BinaryOperation(self.operation, results)
220 local subs = factoredsubs:getsubexpressionsrec()
221 for index, sub in ipairs(subs) do
222 local substituted = factoredsubs:substitute({[sub]=SymbolExpression("_")}):autosimplify()
223 local polynomial, result = substituted:topolynomial()
224 if result then
225 local factored = polynomial:factor():autosimplify()
226 if factored ~= substituted then
227 return factored:substitute({[SymbolExpression("_")]=sub})
228 end
229 end
230 end
231
232 -- Pulls common sub-expressions out of sum expressions
233 if self.operation == BinaryOperation.ADD then
234 local gcf
235 for _, expression in ipairs(factoredsubs:subexpressions()) do
236 if expression.operation ~= BinaryOperation.MUL then
237 expression = BinaryOperation.MULEXP({expression})
238 end
239 if not gcf then
240 gcf = expression
241 else
242 local newgcf = Integer.one()
243 for _, gcfterm in ipairs(gcf:subexpressions()) do
244 local gcfpower = Integer.one()
245 if gcfterm:type() == BinaryOperation and gcfterm.operation == BinaryOperation.POW and gcfterm.expressions[2]:type() == Integer then
246 gcfpower = gcfterm.expressions[2]
247 gcfterm = gcfterm.expressions[1]
248 end
249 for _, term in ipairs(expression:subexpressions()) do
250 local power = Integer.one()
251 if term:type() == BinaryOperation and term.operation == BinaryOperation.POW and term.expressions[2]:type() == Integer then
252 power = term.expressions[2]
253 term = term.expressions[1]
254 end
255 if term == gcfterm then
256 newgcf = newgcf * term^Integer.min(power, gcfpower)
257 end
258 end
259 end
260 gcf = newgcf
261 end
262 end
263 if gcf:type() ~= Integer then
264 local out = Integer.zero()
265 for _, expression in ipairs(factoredsubs:subexpressions()) do
266 out = out + expression/gcf
267 end
268 out = gcf*(out:autosimplify():factor())
269 return out:autosimplify()
270 end
271 end
272
273 return factoredsubs
274 end
275
276 --- @return Expression
277 function BinaryOperation:combine()
278 local den, num, aux, mul, input = {}, {}, {}, {}, self:autosimplify():expand()
279 if input.operation ~= BinaryOperation.ADD then
280 return input
281 end
282 for _, expr in ipairs(input.expressions) do
283 local numpart, denpart = Integer.one(), Integer.one()
284 if expr.operation == BinaryOperation.POW and expr.expressions[2]:type() == Integer and expr.expressions[2] < Integer.zero() then
285 denpart = denpart*expr.expressions[1] ^ expr.expressions[2]:neg()
286 for index,term in ipairs(den) do
287 if expr.expressions[1] == den[index] then
288 if expr.expressions[2]:neg() > mul[index] then
289 mul[index] = expr.expressions[2]:neg()
290 goto continue
291 else
292 goto continue
293 end
294 end
295 end
296 table.insert(den,expr.expressions[1])
297 table.insert(mul,expr.expressions[2]:neg())
298 ::continue::
299 end
300 if expr.operation == BinaryOperation.MUL then
301 for _,subexpr in ipairs(expr.expressions) do
302 if subexpr.operation == BinaryOperation.POW and subexpr.expressions[2]:type() == Integer and subexpr.expressions[2] < Integer.zero() then
303 denpart = denpart*subexpr.expressions[1] ^ subexpr.expressions[2]:neg()
304 for index,term in ipairs(den) do
305 if subexpr.expressions[1] == den[index] then
306 if subexpr.expressions[2]:neg() > mul[index] then
307 mul[index] = subexpr.expressions[2]:neg()
308 goto continue
309 else
310 goto continue
311 end
312 end
313 end
314 table.insert(den,subexpr.expressions[1])
315 table.insert(mul,subexpr.expressions[2]:neg())
316 ::continue::
317 else
318 numpart = numpart*subexpr
319 end
320 end
321 end
322 if expr.operation ~= BinaryOperation.POW and expr.operation ~= BinaryOperation.MUL then
323 numpart = expr
324 end
325 table.insert(num,numpart)
326 table.insert(aux,denpart)
327 end
328 local denominator = Integer.one()
329 local numerator = Integer.zero()
330 for index,expr in ipairs(den) do
331 denominator = denominator*den[index] ^ mul[index]
332 end
333 denominator = denominator:autosimplify()
334 for index,expr in ipairs(num) do
335 local uncommon = denominator/aux[index]
336 uncommon = uncommon:factor():simplify()
337 numerator = numerator + expr*uncommon
338 end
339 numerator = numerator:simplify():factor()
340 if denominator == Integer.one() then
341 return numerator
342 else
343 return numerator/denominator
344 end
345 end
346
347 --- @param collect Expression
348 --- @return Expression
349 function BinaryOperation:collect(collect)
350 -- Constant expressions cannot be collected
351 if collect:isconstant() then
352 return self
353 end
354
355 -- Recusively collect subexpressions
356 local results = {}
357 for index, expression in ipairs(self:subexpressions()) do
358 results[index] = expression:collect(collect)
359 end
360 local collected = BinaryOperation(self.operation, results)
361
362 if not (collected.operation == BinaryOperation.ADD) then
363 return collected:autosimplify()
364 end
365
366 local coefficients = {}
367
368 -- TODO: Add an expression map class
369 setmetatable(coefficients, {__index =
370 function(table, key)
371 local out = rawget(table, tostring(key))
372 return out or Integer.zero()
373 end,
374 __newindex =
375 function (table, key, value)
376 rawset(table, tostring(key), value)
377 end
378 })
379
380 -- Finds all instances of a constant power of the expression to be collected, and maps each power to all terms it is multiplied by
381 for _, expression in ipairs(collected:subexpressions()) do
382 if expression == collect then
383 coefficients[Integer.one()] = coefficients[Integer.one()] + Integer.one()
384 elseif expression.operation == BinaryOperation.POW and expression:subexpressions()[1] == collect and expression:subexpressions()[2]:isconstant() then
385 coefficients[expression:subexpressions()[2]] = coefficients[expression:subexpressions()[2]] + Integer.one()
386 elseif collect:type() == BinaryOperation and collect.operation == BinaryOperation.POW and
387 expression.operation == BinaryOperation.POW and expression:subexpressions()[1] == collect:subexpressions()[1] then
388 -- Handle the fact that autosimplify turns (a^x^n -> a^(xn)), this is needed if the term to collect is itself an exponential
389 local power = (expression:subexpressions()[2] / collect:subexpressions()[2]):autosimplify()
390 if power:isconstant() then
391 coefficients[power] = coefficients[power] + Integer.one()
392 else
393 coefficients[Integer.zero()] = coefficients[Integer.zero()] + expression
394 end
395 elseif expression.operation == BinaryOperation.MUL then
396 local varpart
397 local coeffpart = Integer.one()
398 for _, term in ipairs(expression:subexpressions()) do
399 if term == collect then
400 varpart = Integer.one()
401 elseif (term.operation == BinaryOperation.POW and term:subexpressions()[1] == collect and term:subexpressions()[2]:isconstant()) then
402 varpart = term:subexpressions()[2]
403 elseif collect:type() == BinaryOperation and collect.operation == BinaryOperation.POW and
404 term.operation == BinaryOperation.POW and term:subexpressions()[1] == collect:subexpressions()[1] then
405 local power = (term:subexpressions()[2] / collect:subexpressions()[2]):autosimplify()
406 if power:isconstant() then
407 varpart = power
408 end
409 else
410 coeffpart = coeffpart * term
411 end
412 end
413 if varpart then
414 coefficients[varpart] = coefficients[varpart] + coeffpart
415 else
416 coefficients[Integer.zero()] = coefficients[Integer.zero()] + expression
417 end
418 else
419 coefficients[Integer.zero()] = coefficients[Integer.zero()] + expression
420 end
421
422
423 end
424
425 local out = Integer.zero()
426 for index, value in pairs(coefficients) do
427 out = out + collect ^ Rational.fromstring(index) * value
428 end
429
430 return out:autosimplify()
431 end
432
433 --- @param other Expression
434 --- @return boolean
435 function BinaryOperation:order(other)
436 if other:isconstant() then
437 return false
438 end
439
440 if other:isatomic() then
441 if self.operation == BinaryOperation.POW then
442 return self:order(BinaryOperation(BinaryOperation.POW, {other, Integer.one()}))
443 end
444
445 if self.operation == BinaryOperation.MUL then
446 return self:order(BinaryOperation(BinaryOperation.MUL, {other}))
447 end
448
449 if self.operation == BinaryOperation.ADD then
450 return self:order(BinaryOperation(BinaryOperation.ADD, {other}))
451 end
452 end
453
454 if self.operation == BinaryOperation.POW and other.operation == BinaryOperation.POW then
455 if self.expressions[1] ~= other.expressions[1] then
456 return self.expressions[1]:order(other.expressions[1])
457 end
458 return self.expressions[2]:order(other.expressions[2])
459 end
460
461 if (self.operation == BinaryOperation.MUL and other.operation == BinaryOperation.MUL) or
462 (self.operation == BinaryOperation.ADD and other.operation == BinaryOperation.ADD) then
463 local k = 0
464 while #self.expressions - k > 0 and #other.expressions - k > 0 do
465 if self.expressions[#self.expressions - k] ~= other.expressions[#other.expressions - k] then
466 return self.expressions[#self.expressions - k]:order(other.expressions[#other.expressions - k])
467 end
468 k = k + 1
469 end
470 return #self.expressions < #other.expressions
471 end
472
473 if (self.operation == BinaryOperation.MUL) and (other.operation == BinaryOperation.POW or other.operation == BinaryOperation.ADD) then
474 return self:order(BinaryOperation(BinaryOperation.MUL, {other}))
475 end
476
477 if (self.operation == BinaryOperation.POW) and (other.operation == BinaryOperation.MUL) then
478 return BinaryOperation(BinaryOperation.MUL, {self}):order(other)
479 end
480
481 if (self.operation == BinaryOperation.POW) and (other.operation == BinaryOperation.ADD) then
482 return self:order(BinaryOperation(BinaryOperation.POW, {other, Integer.one()}))
483 end
484
485 if (self.operation == BinaryOperation.ADD) and (other.operation == BinaryOperation.MUL) then
486 return BinaryOperation(BinaryOperation.MUL, {self}):order(other)
487 end
488
489 if (self.operation == BinaryOperation.ADD) and (other.operation == BinaryOperation.POW) then
490 return BinaryOperation(BinaryOperation.POW, {self, Integer.one()}):order(other)
491 end
492
493 if other:type() == FunctionExpression or other:type() == TrigExpression or other:type() == Logarithm then
494 if self.operation == BinaryOperation.ADD or self.operation == BinaryOperation.MUL then
495 return self:order(BinaryOperation(self.operation, {other}))
496 end
497
498 if self.operation == BinaryOperation.POW then
499 return self:order(other^Integer.one())
500 end
501 end
502
503 return true
504 end
505
506 --- Returns whether the binary operation is commutative.
507 --- @return boolean
508 function BinaryOperation:iscommutative()
509 error("Called unimplemented method: iscommutative()")
510 end
511
512 --- @return PolynomialRing, boolean
513 function BinaryOperation:topolynomial()
514 local addexp = self
515 if not self.operation or self.operation ~= BinaryOperation.ADD then
516 addexp = BinaryOperation(BinaryOperation.ADD, {self})
517 end
518
519 local poly = {}
520 local degree = 0
521 local symbol
522 for _, expression in ipairs(addexp.expressions) do
523 local coefficient
524 local sym
525 local power
526 -- Expressions of the form c
527 if expression:isconstant() then
528 coefficient = expression
529 power = 0
530 -- Expressions of the form x
531 elseif expression:type() == SymbolExpression then
532 coefficient = Integer.one()
533 sym = expression.symbol
534 power = 1
535 -- Expressions of the form c*x
536 elseif expression.operation and expression.operation == BinaryOperation.MUL and #expression.expressions == 2
537 and expression.expressions[1]:isconstant() and expression.expressions[2]:type() == SymbolExpression then
538
539 coefficient = expression.expressions[1]
540 sym = expression.expressions[2].symbol
541 power = 1
542 -- Expressions of the form c*x^n (totally not confusing)
543 elseif expression.operation and expression.operation == BinaryOperation.MUL and #expression.expressions == 2
544 and expression.expressions[1]:isconstant() and expression.expressions[2].operation and
545 expression.expressions[2].operation == BinaryOperation.POW and #expression.expressions[2].expressions == 2
546 and expression.expressions[2].expressions[1]:type() == SymbolExpression and expression.expressions[2].expressions[2].getring
547 and expression.expressions[2].expressions[2]:getring() == Integer.getring() and expression.expressions[2].expressions[2] > Integer.zero() then
548
549 coefficient = expression.expressions[1]
550 sym = expression.expressions[2].expressions[1].symbol
551 power = expression.expressions[2].expressions[2]:asnumber()
552 -- Expressions of the form x^n
553 elseif expression.operation and expression.operation == BinaryOperation.POW and #expression.expressions == 2
554 and expression.expressions[1]:type() == SymbolExpression and expression.expressions[2].getring
555 and expression.expressions[2]:getring() == Integer.getring() and expression.expressions[2] > Integer.zero() then
556
557 coefficient = Integer.one()
558 sym = expression.expressions[1].symbol
559 power = expression.expressions[2]:asnumber()
560 else
561 return self, false
562 end
563
564 if symbol and sym and symbol ~= sym then
565 return self, false
566 end
567 if not symbol then
568 symbol = sym
569 end
570 poly[power + 1] = coefficient
571 if power > degree then
572 degree = power
573 end
574 end
575
576 for i = 1,degree+1 do
577 poly[i] = poly[i] or Integer.zero()
578 end
579
580 return PolynomialRing(poly, symbol), true
581 end
582
583 function BinaryOperation:tolatex()
584 if self.operation == BinaryOperation.POW then
585 if self.expressions[2]:type() == Integer and self.expressions[2] < Integer.zero() then
586 local base = self.expressions[1]
587 local exponent = self.expressions[2]
588 if exponent == Integer(-1) then
589 return "\\frac{1}{" .. base:tolatex() .. "}"
590 else
591 if base:isatomic() then
592 return "\\frac{1}{" .. base:tolatex() .. "^{" .. exponent:neg():tolatex() .. "}}"
593 else
594 return "\\frac{1}{\\left(" .. base:tolatex() .. "\\right)^{" .. exponent:neg():tolatex() .. "}}"
595 end
596 end
597 end
598 if self.expressions[1]:isatomic() then
599 if self.expressions[2]:isconstant() and self.expressions[2]:getring() == Rational:getring() and self.expressions[2].numerator == Integer.one() then
600 if self.expressions[2].denominator == Integer(2) then
601 return "\\sqrt{" .. self.expressions[1]:tolatex() .. '}'
602 end
603 return "\\sqrt[" .. self.expressions[2].denominator:tolatex() .. ']{' .. self.expressions[1]:tolatex() .. '}'
604 end
605 return self.expressions[1]:tolatex() .. '^{' .. self.expressions[2]:tolatex() .. '}'
606 else
607 if self.expressions[2]:isconstant() and self.expressions[2]:getring() == Rational:getring() and self.expressions[2].numerator == Integer.one() then
608 if self.expressions[2].denominator == Integer(2) then
609 return "\\sqrt{" .. self.expressions[1]:tolatex() .. '}'
610 end
611 return "\\sqrt[" .. self.expressions[2].denominator:tolatex() .. ']{' .. self.expressions[1]:tolatex() .. '}'
612 end
613 return "\\left(" .. self.expressions[1]:tolatex() .. "\\right)" .. '^{' .. self.expressions[2]:tolatex() .. '}'
614 end
615 end
616 if self.operation == BinaryOperation.MUL then
617 local sign = ''
618 local out = ''
619 local denom = ''
620 if self:autosimplify():isconstant() then
621 for index, expression in ipairs(self.expressions) do
622 if index == 1 then
623 out = out .. expression:tolatex()
624 elseif expression:isconstant() and expression < Integer.zero() then
625 out = out .. "\\cdot (" .. expression:tolatex() .. ")"
626 else
627 out = out .. "\\cdot " .. expression:tolatex()
628 end
629 end
630 return out
631 end
632 if #self.expressions == 2 and self.expressions[2]:type() == BinaryOperation and self.expressions[2].operation == BinaryOperation.POW and self.expressions[2].expressions[2] == -Integer.one() then
633 out = '\\frac{' .. self.expressions[1]:tolatex() .. '}{' .. self.expressions[2].expressions[1]:tolatex() .. '}'
634 return out
635 end
636 for _, expression in ipairs(self.expressions) do
637 if expression:type() == BinaryOperation then
638 if expression.operation == BinaryOperation.POW and expression.expressions[2]:isconstant() and expression.expressions[2] < Integer.zero() then
639 local reversed = (Integer.one() / expression):autosimplify()
640 if reversed.operation == BinaryOperation.ADD or expression.operation == BinaryOperation.SUB then
641 denom = denom .. '\\left('.. reversed:tolatex() .. '\\right)'
642 else
643 denom = denom .. reversed:tolatex()
644 end
645 elseif expression.operation == BinaryOperation.ADD or expression.operation == BinaryOperation.SUB then
646 out = out .. '\\left(' .. expression:tolatex() .. '\\right)'
647 else
648 out = out .. expression:tolatex()
649 end
650 else
651 if expression == Integer(-1) then
652 out = out .. '-'
653 elseif expression:type() == Rational and expression.numerator == Integer.one() then
654 denom = denom .. expression.denominator:tolatex()
655 elseif expression:type() == Rational and expression.numerator == Integer(-1) then
656 out = out .. '-'
657 denom = denom .. expression.denominator:tolatex()
658 elseif expression:type() == Rational then
659 out = out .. expression.numerator:tolatex()
660 denom = denom .. expression.denominator:tolatex()
661 else
662 out = out .. expression:tolatex()
663 end
664 end
665 end
666 if string.sub(out,1,1) == '-' then
667 sign = '-'
668 out = string.sub(out,2,-1)
669 end
670 if denom ~= '' and out == '' then
671 return sign .. '\\frac{' .. '1' .. '}{' .. denom .. '}'
672 end
673 if denom ~= '' then
674 return sign .. '\\frac{' .. out .. '}{' .. denom .. '}'
675 end
676 return sign..out
677 end
678 if self.operation == BinaryOperation.ADD then
679 local out = ''
680 for index, expression in ipairs(self.expressions) do
681 out = out .. expression:tolatex()
682 if self.expressions[index + 1] and string.sub(self.expressions[index + 1]:tolatex(), 1, 1) ~= "-" then
683 out = out .. '+'
684 end
685 end
686 return out
687 end
688 if self.operation == BinaryOperation.DIV then
689 return '\\frac{' .. self.expressions[1]:tolatex() .. '}{' .. self.expressions[2]:tolatex() .. '}'
690 end
691 if self.operation == BinaryOperation.SUB then
692 local out = ''
693 if not self.expressions[2] then
694 if not self.expressions[1]:isatomic() then
695 out = '-\\left(' .. self.expressions[1]:tolatex() .. '\\right)'
696 else
697 out = '-' .. self.expressions[1]:tolatex()
698 end
699 else
700 for index, expression in ipairs(self.expressions) do
701 if expression.operation and (expression.operation == BinaryOperation.ADD or expression.operation == BinaryOperation.SUB) and index >1 then
702 out = out .. "\\left(" .. expression:tolatex() .. "\\right)"
703 else
704 out = out .. expression:tolatex()
705 end
706 if self.expressions[index + 1] then
707 out = out .. '-'
708 end
709 end
710 end
711 return out
712 end
713 return self
714 end
715
716 -----------------
717 -- Inheritance --
718 -----------------
719
720 __BinaryOperation.__index = CompoundExpression
721 __BinaryOperation.__call = BinaryOperation.new
722 BinaryOperation = setmetatable(BinaryOperation, __BinaryOperation)
723
724 ----------------------
725 -- Static constants --
726 ----------------------
727
728 BinaryOperation.ADD = function(a, b)
729 return a + b
730 end
731
732 BinaryOperation.SUB = function(a, b)
733 return a - b
734 end
735
736 BinaryOperation.MUL = function(a, b)
737 return a * b
738 end
739
740 BinaryOperation.DIV = function(a, b)
741 return a / b
742 end
743
744 BinaryOperation.IDIV = function(a, b)
745 return a // b
746 end
747
748 BinaryOperation.MOD = function(a, b)
749 return a % b
750 end
751
752 BinaryOperation.POW = function(a, b)
753 return a ^ b
754 end
755
756 BinaryOperation.DEFAULT_NAMES = {
757 [BinaryOperation.ADD] = "+",
758 [BinaryOperation.SUB] = "-",
759 [BinaryOperation.MUL] = "*",
760 [BinaryOperation.DIV] = "/",
761 [BinaryOperation.IDIV] = "//",
762 [BinaryOperation.MOD] = "%",
763 [BinaryOperation.POW] = "^"
764 }
765
766 BinaryOperation.COMMUTATIVITY = {
767 [BinaryOperation.ADD] = true,
768 [BinaryOperation.SUB] = false,
769 [BinaryOperation.MUL] = true,
770 [BinaryOperation.DIV] = false,
771 [BinaryOperation.IDIV] = false,
772 [BinaryOperation.MOD] = false,
773 [BinaryOperation.POW] = false
774 }
775
776 BinaryOperation.ADDEXP = function(expressions, name)
777 return BinaryOperation(BinaryOperation.ADD, expressions, name)
778 end
779
780 BinaryOperation.SUBEXP = function(expressions, name)
781 return BinaryOperation(BinaryOperation.SUB, expressions, name)
782 end
783
784 BinaryOperation.MULEXP = function(expressions, name)
785 return BinaryOperation(BinaryOperation.MUL, expressions, name)
786 end
787
788 BinaryOperation.DIVEXP = function(expressions, name)
789 return BinaryOperation(BinaryOperation.DIV, expressions, name)
790 end
791
792 BinaryOperation.IDIVEXP = function(expressions, name)
793 return BinaryOperation(BinaryOperation.IDIV, expressions, name)
794 end
795
796 BinaryOperation.MODEXP = function(expressions, name)
797 return BinaryOperation(BinaryOperation.MOD, expressions, name)
798 end
799
800 BinaryOperation.POWEXP = function(expressions, name)
801 return BinaryOperation(BinaryOperation.POW, expressions, name)
802 end