Mapytex/mapytex/calculus/core/evaluate.py

54 lines
1.1 KiB
Python
Raw Normal View History

2018-01-21 15:16:08 +00:00
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 lafrite <lafrite@Poivre>
#
# Distributed under terms of the MIT license.
"""
Evaluating a binary tree
"""
from .operator import OPERATORS
2018-03-07 13:26:06 +00:00
class ComputeError(Exception):
pass
2018-01-21 15:16:08 +00:00
def compute(node, left_v, right_v):
"""
Computing a node
:example:
>>> compute("+", 1, 2)
3
>>> compute("-", None, 2)
-2
2018-03-07 13:26:06 +00:00
>>> compute("-", 1, 2)
Traceback (most recent call last):
...
mapytex.calculus.core.evaluate.ComputeError: left_v need to be None for operator with arity 1
2018-01-21 15:16:08 +00:00
"""
op = OPERATORS[node]
lv = left_v
rv = right_v
2018-03-07 13:26:06 +00:00
if op['arity'] == 1:
if lv is None:
return op["operate"](rv)()
else:
raise ComputeError("left_v need to be None for operator with arity 1")
else:
try:
return op["operate"](lv)(rv)
except NotImplemented:
return op["roperate"](rv)(lv)
2018-01-21 15:16:08 +00:00
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del