Feat: tokens can operate with builtin int

This commit is contained in:
Bertrand Benjamin 2019-10-13 22:03:29 +02:00
parent fbfaeb5a58
commit 6b353d2dd0
1 changed files with 78 additions and 2 deletions

View File

@ -11,6 +11,7 @@ Tokens: practical envelop of math object
"""
from ..renders import renders
from ...core.MO.atoms import moify
class Token(object):
@ -26,7 +27,11 @@ class Token(object):
self._ancestor = ancestor
@classmethod
def random(cls):
def random(
cls,
family="integer",
**kwds
):
raise NotImplemented
@classmethod
@ -86,7 +91,10 @@ class Token(object):
from . import factory
if not isinstance(other, Token):
_other = factory(other)
try:
_other = factory(other)
except AttributeError:
_other = factory(Expression(moify(other)))
else:
_other = other
tree = Tree(operation, self._mo, _other._mo)
@ -106,6 +114,14 @@ class Token(object):
... print(i)
3 + 7
10
>>> a = Integer(3)
>>> c = a + 7
>>> c
<Integer 10>
>>> for i in c.explain():
... print(i)
3 + 7
10
>>> from .number import Fraction
>>> a = Fraction("4/3")
>>> b = Integer(7)
@ -137,6 +153,9 @@ class Token(object):
... print(i)
3 * 7
21
>>> c = a * 7
>>> c
<Integer 21>
>>> from .number import Fraction
>>> a = Fraction("4/3")
>>> b = Integer(7)
@ -164,6 +183,9 @@ class Token(object):
>>> for i in c.explain():
... print(i)
3 / 7
>>> c = a / 7
>>> c
<Fraction 3 / 7>
>>> from .number import Fraction
>>> a = Fraction("4/3")
>>> b = Integer(7)
@ -179,6 +201,60 @@ class Token(object):
"""
return self._operate(other, "/")
def _roperate(self, other, operation):
""" Make a operation between 2 Tokens """
from ..expression import Expression
from ...core import Tree
from . import factory
if not isinstance(other, Token):
try:
_other = factory(other)
except AttributeError:
_other = factory(Expression(moify(other)))
else:
_other = other
tree = Tree(operation, _other._mo, self._mo)
return Expression(tree).simplify()
def __radd__(self, other):
""" Adding 2 Tokens or a Token and a Expression
:example:
>>> from .number import Integer
>>> a = Integer(3)
>>> c = 7 + a
>>> c
<Integer 10>
"""
return self._roperate(other, "+")
def __rmul__(self, other):
""" Multiply 2 Tokens or a Token and a Expression
:example:
>>> from .number import Integer
>>> a = Integer(3)
>>> c = 7 * a
>>> c
<Integer 21>
"""
return self._roperate(other, "*")
def __rtruediv__(self, other):
""" Divising 2 Tokens or a Token and a Expression
:example:
>>> from .number import Integer
>>> a = Integer(3)
>>> c = 7 / a
>>> c
<Fraction 7 / 3>
"""
return self._roperate(other, "/")
def _get_soul(self, other=None):
""" Get the builtin soul of self or other """
if isinstance(other, Token):