Decorator for computing special cases

This commit is contained in:
2018-03-17 11:55:32 +03:00
parent f4422c6d1a
commit 3f3e52cdf8
4 changed files with 134 additions and 34 deletions

View File

@@ -10,13 +10,14 @@
Adding MO
"""
from functools import wraps
from multipledispatch import Dispatcher
from ..tree import Tree
from ..MO.mo import MO, MOnumber
from ..MO.fraction import MOFraction
from .exceptions import AddError
from .arithmetic import lcm
from .type_filter import args_are
from .filters import special_case
add_doc = """ Adding MOs
@@ -25,9 +26,36 @@ add_doc = """ Adding MOs
:return: Tree or MO
"""
add = Dispatcher("add", doc=add_doc)
def add_filter(left, right):
""" Automatic add on MO
:param left: MO
:param right: MO
:returns: MO if it is a special case, nothing other wise
>>> a = MOnumber(0)
>>> b = MOFraction(1, 2)
>>> add(a, b)
<MOFraction 1 / 2>
>>> add(b, a)
<MOFraction 1 / 2>
"""
try:
if left == 0:
return right
except TypeError:
pass
try:
if right == 0:
return left
except TypeError:
pass
@add.register(MOnumber, MOnumber)
@special_case(add_filter)
def monumber_monumber(left, right):
""" Simply add MO value
@@ -40,6 +68,7 @@ def monumber_monumber(left, right):
return MO.factory(left.value + right.value)
@add.register(MOnumber, MOFraction)
@special_case(add_filter)
def monumber_mofraction(left, right):
""" Return a tree with the MOnumber transformed into a MOFraction
@@ -58,6 +87,7 @@ def monumber_mofraction(left, right):
return Tree("+", left_fraction, right)
@add.register(MOFraction, MOnumber)
@special_case(add_filter)
def mofraction_monumber(left, right):
""" Return a tree with the MOnumber transformed into a MOFraction
@@ -76,6 +106,7 @@ def mofraction_monumber(left, right):
return Tree("+", left, right_fraction)
@add.register(MOFraction, MOFraction)
@special_case(add_filter)
def mofraction_mofraction(left, right):
""" 3 differents cases: