Feat(API): +*/ for Tokens

This commit is contained in:
Bertrand Benjamin 2018-12-13 13:45:39 +01:00
parent c9fe2ede7d
commit ef371401e6
2 changed files with 93 additions and 11 deletions

View File

@ -92,7 +92,7 @@ class Fraction(Token):
if not isinstance(a, MO):
if isinstance(a, str):
num, denom = a.split('/')
mo = MOFraction(num, denom)
mo = MOFraction(int(num), int(denom))
else:
raise TypeError
else:

View File

@ -63,13 +63,10 @@ class Token(object):
def __tex__(self):
return self._mo.__tex__
def __add__(self, other):
""" Adding 2 Tokens or a Token and a Expression
:example:
>>> from .number import Integer
>>> a = Integer(3)
def _operate(self, other, operation):
""" Make a operation between 2 Tokens,
a Token and en Expression ora
a Token an a builtin type
"""
from ..expression import Expression
from ...core import Tree
@ -78,10 +75,95 @@ class Token(object):
_other = factory(other)
else:
_other = other
tree = Tree('+', self.mo, _other.mo)
ans = Expression(tree).simplify()
return ans
tree = Tree(operation, self._mo, _other._mo)
return Expression(tree).simplify()
def __add__(self, other):
""" Adding 2 Tokens or a Token and a Expression
:example:
>>> from .number import Integer
>>> a = Integer(3)
>>> b = Integer(7)
>>> c = a + b
>>> c
<Integer 10>
>>> for i in c.explain():
... print(i)
3 + 7
10
>>> from .number import Fraction
>>> a = Fraction("4/3")
>>> b = Integer(7)
>>> c = a + b
>>> c
<Fraction 25 / 3>
>>> for i in c.explain():
... print(i)
4 / 3 + 7
4 / 3 + 7 / 1
4 / 3 + (7 * 3) / (1 * 3)
4 / 3 + 21 / 3
(4 + 21) / 3
25 / 3
"""
return self._operate(other, "+")
def __mul__(self, other):
""" Multiply 2 Tokens or a Token and a Expression
:example:
>>> from .number import Integer
>>> a = Integer(3)
>>> b = Integer(7)
>>> c = a * b
>>> c
<Integer 21>
>>> for i in c.explain():
... print(i)
3 * 7
21
>>> from .number import Fraction
>>> a = Fraction("4/3")
>>> b = Integer(7)
>>> c = a * b
>>> c
<Fraction 28 / 3>
>>> for i in c.explain():
... print(i)
4 / 3 * 7
(4 * 7) / 3
28 / 3
"""
return self._operate(other, "*")
def __truediv__(self, other):
""" Divising 2 Tokens or a Token and a Expression
:example:
>>> from .number import Integer
>>> a = Integer(3)
>>> b = Integer(7)
>>> c = a / b
>>> c
<Fraction 3 / 7>
>>> for i in c.explain():
... print(i)
3 / 7
>>> from .number import Fraction
>>> a = Fraction("4/3")
>>> b = Integer(7)
>>> c = a / b
>>> c
<Fraction 4 / 21>
>>> for i in c.explain():
... print(i)
4 / 3 / 7
4 / 3 * 1 / 7
(4 * 1) / (3 * 7)
4 / 21
"""
return self._operate(other, "/")