Feat(API): Expression.from_str tries to build a token when it's

possible
This commit is contained in:
Bertrand Benjamin 2018-12-13 09:29:44 +01:00
parent bcf589c607
commit 780772ec2d

View File

@ -41,14 +41,38 @@ class Expression(object):
self._ancestor = ancestor self._ancestor = ancestor
@classmethod @classmethod
def from_str(cls, string): def from_str(cls, string, typing=True):
""" Initiate the expression from a string """ Initiate the expression from a string
:param string: String to parse to generate the Expression :param string: String to parse to generate the Expression
:returns: the expression :returns: the expression
:example:
>>> e = Expression.from_str("2 + 3 * 4")
>>> e
<Exp: 2 + 3 * 4>
>>> e = Expression.from_str("2/3")
>>> e
<Fraction 2 / 3>
>>> e = Expression.from_str("2x + 1")
>>> e
<Linear 2x + 1>
>>> e = Expression.from_str("2x + 1 + 5x^2")
>>> e
<Quadratic 2x + 1 + 5x^2>
>>> e = Expression.from_str("2x + 1 + 5x")
>>> e
<Exp: 2x + 1 + 5x>
""" """
t = Tree.from_str(string) t = Tree.from_str(string)
if typing:
tt = cls(t)._typing()
try:
return factory(tt)
except TypeError as e:
return cls(t)
return cls(t) return cls(t)
@classmethod @classmethod
@ -173,7 +197,7 @@ class Expression(object):
""" Build a copy of self with as much typing as possible """ Build a copy of self with as much typing as possible
:example: :example:
>>> e = Expression.from_str("2x") >>> e = Expression.from_str("2x", typing=False)
>>> print(e._tree.map_on_leaf(type)) >>> print(e._tree.map_on_leaf(type))
* *
> <class 'mapytex.calculus.core.MO.mo.MOnumber'> > <class 'mapytex.calculus.core.MO.mo.MOnumber'>
@ -185,7 +209,7 @@ class Expression(object):
>>> print(type(typed_e._tree)) >>> print(type(typed_e._tree))
<class 'mapytex.calculus.core.MO.monomial.MOMonomial'> <class 'mapytex.calculus.core.MO.monomial.MOMonomial'>
>>> e = Expression.from_str("2x+3+4/5") >>> e = Expression.from_str("2x+3+4/5", typing=False)
>>> print(e._tree.map_on_leaf(type)) >>> print(e._tree.map_on_leaf(type))
+ +
> + > +