Fix: move __call__ to expressions

This commit is contained in:
Bertrand Benjamin 2019-07-15 18:37:16 +02:00
parent 23ab39f7d4
commit 04ac74d17a
2 changed files with 41 additions and 28 deletions

View File

@ -10,6 +10,7 @@
Expression
"""
from functools import partial
from ..core import AssocialTree, Tree, compute, typing, TypingError
from ..core.random import extract_rdleaf, extract_rv, random_generator, compute_leafs, replace_rdleaf
from ..core.MO import moify
@ -438,6 +439,45 @@ class Expression(object):
else:
yield self
def __call__(self, value):
""" Call a Expression to evaluate itself on value
:examples:
>>> f = Expression.from_str("3*x^2 + 2x + 1")
>>> for s in f(2).explain():
... print(s)
3 * 2^2 + 2 * 2 + 1
3 * 4 + 4 + 1
12 + 5
17
"""
tree = self._tree
variable = (set(tree.get_leafs(extract_variable)) - {None}).pop()
dest = moify(value)
replace_var = partial(replace, origin=variable, dest=dest)
tree = tree.map_on_leaf(replace_var)
return Expression(tree).simplify()
def extract_variable(leaf):
try:
return leaf.variable
except AttributeError:
return None
def replace(leaf, origin, dest):
""" Recursively replace origin to dest in leaf """
try:
leaf.tree
except AttributeError:
if leaf == origin:
return dest
return leaf
replace_var = partial(replace, origin=origin, dest=dest)
return leaf.tree.map_on_leaf(replace_var)
# -----------------------------
# Reglages pour 'vim'

View File

@ -11,7 +11,6 @@ Tokens representing polynomials functions
"""
from ..expression import Expression
from functools import partial
from .token import Token
from ...core.MO import MO
from ...core.MO.atoms import moify
@ -93,14 +92,7 @@ class Polynomial(Token):
12 + 5
17
"""
tree = self._mo.tree
variable = (set(tree.get_leafs(extract_variable)) - {None}).pop()
dest = moify(value)
replace_var = partial(replace, origin=variable, dest=dest)
tree = tree.map_on_leaf(replace_var)
return Expression(tree).simplify()
return Expression(self._mo.tree)(value)
def differentiate(self):
""" Differentiate a polynome
@ -262,25 +254,6 @@ class Quadratic(Polynomial):
else:
raise NotImplementedError("Todo!")
def extract_variable(leaf):
try:
return leaf.variable
except AttributeError:
return None
def replace(leaf, origin, dest):
""" Recursively replace origin to dest in leaf """
try:
leaf.tree
except AttributeError:
if leaf == origin:
return dest
return leaf
replace_var = partial(replace, origin=origin, dest=dest)
return leaf.tree.map_on_leaf(replace_var)
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: