Mapytex/mapytex/calculus/core/compute/minus.py

100 lines
2.1 KiB
Python

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
"""
Minus MO: take the opposit
"""
from ..MO.mo import MO, MOnumber
from ..MO.fraction import MOFraction
from .exceptions import MinusError
def minus(left, right):
""" Perform the minusition of left and right
:param left: left MO
:param right: right MO
:returns: Tree or MO
>>> a = MOnumber(4)
>>> minus(None, a)
<MOnumber - 4>
>>> a = MOnumber(-4)
>>> minus(None, a)
<MOnumber 4>
>>> b = MOnumber(0)
>>> minus(None, b)
<MOnumber 0>
"""
if not left is None:
raise MinusError(f"'-' is a 1 arity operator, left should be None (got {left})")
return MINUSFUNCTIONS[type(right)](right)
def monumber(right):
""" Minusing monumber
:param right: right MOnumber
:returns: MONumber
>>> a = MOnumber(4)
>>> monumber(a)
<MOnumber - 4>
"""
return MO.factory(- right.value)
def mofraction(right):
""" Minusing a mofraction
:param right: a mofraction
:returns: Tree with the number converted into a mofraction
>>> a = MOFraction(6, 5)
>>> print(mofraction(a))
-
> None
> /
| > 6
| > 5
>>> a = MOFraction(6, 5, True)
>>> print(mofraction(a))
/
> 6
> 5
"""
if right.negative:
return MOFraction(right._numerator, right._denominator)
try:
if right._numerator < 0:
return MOFraction(-right._numerator, right._denominator)
except TypeError:
pass
try:
if right._denominator < 0:
return MOFraction(right._numerator, -right._denominator)
except TypeError:
pass
return MOFraction(right._numerator, right._denominator, True)
# TODO: Faire un décorateur pour un enregistrement automatique |dim. mars 11 18:24:32 EAT 2018
MINUSFUNCTIONS = {
MOnumber: monumber,
MOFraction: mofraction,
}
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del