Mapytex/mapytex/calculus/core/evaluate.py

54 lines
1.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.
"""
Evaluating a binary tree
"""
from .operator import OPERATORS
class ComputeError(Exception):
pass
def compute(node, left_v, right_v):
"""
Computing a node
:example:
>>> compute("+", 1, 2)
3
>>> compute("-", None, 2)
-2
>>> compute("-", 1, 2)
Traceback (most recent call last):
...
mapytex.calculus.core.evaluate.ComputeError: left_v need to be None for operator with arity 1
"""
op = OPERATORS[node]
lv = left_v
rv = right_v
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)
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del