Mapytex/mapytex/calculus/random/core/str2.py

66 lines
1.8 KiB
Python

from ...core.operator import is_operator
from functools import partial
from ...core.str2 import concurent_broadcast, lookforNumbers, pparser, missing_times, lookfor
from ...core.coroutine import STOOOP
from ...core.MO import moify_cor
from ...core.tree import MutableTree
from .leaf import look_for_rdleaf
def rdstr2(sink):
""" Return a pipeline which parse random expression and with sink as endpoint
:example:
>>> from ...core.str2 import list_sink
>>> rdstr2list = rdstr2(list_sink)
>>> rdstr2list("{a}+{a*b}-2")
[<RdLeaf a>, '+', <RdLeaf a*b>, '+', <MOnumber -2>]
>>> rdstr2list("{a}({b}x+{c})")
[<RdLeaf a>, '*', [<RdLeaf b>, '*', <MOstr x>, '+', <RdLeaf c>]]
"""
lfop = lookfor(is_operator)
operator_corout = partial(concurent_broadcast, lookfors=[lfop])
def pipeline(expression):
str2_corout = look_for_rdleaf(
lookforNumbers(operator_corout(
missing_times(moify_cor(pparser(sink)))))
)
for i in expression.replace(" ", ""):
str2_corout.send(i)
a = str2_corout.throw(STOOOP)
return a
return pipeline
class RandomTree(MutableTree):
""" MutableTree that accept {a} syntax for random generation """
@classmethod
def from_str(cls, expression):
""" Initiate a random tree from a string that need to be parsed
:exemple:
>>> t = RandomTree.from_str("{b}*x+{c}")
>>> print(t)
+
> *
| > {b}
| > x
> {c}
>>> t = RandomTree.from_str("{a}*({b}*x+{c})")
>>> print(t)
*
> {a}
> +
| > *
| | > {b}
| | > x
| > {c}
"""
str_2_mut_tree = rdstr2(cls.sink)
return str_2_mut_tree(expression)