to_string.py 1.48 KB
from support.expr_types import *
from decimal import Decimal

def expr_to_string(expr, use_parens=True, use_spaces=True):
    from support.canonicalize import simplify
    expr = simplify(expr)
    if expr is None:
        return "?"
    if isinstance(expr, Number) or isinstance(expr, Variable):
        if (isinstance(expr, float) or isinstance(expr, Decimal)) and float(expr).is_integer():
            return str(int(float((expr))))
        if isinstance(expr, Decimal):
            return str(float(expr))
        return str(expr)
    elif isinstance(expr, SumOperation):
        return("(" if use_parens else "") +  " + ".join([expr_to_string(x, use_parens=False, use_spaces=False) for x in expr.values]) + (")" if use_parens else "")
    elif isinstance(expr, ProductOperation):
        return " * ".join([expr_to_string(x) for x in expr.values])
    # Commutative binary operations...
    elif isinstance(expr, BinaryOperation):
        use_parens = True
        return ("(" if use_parens else "") + expr_to_string(expr.left) + (" " if use_spaces else "") + expr.op + (" " if use_spaces else "") + expr_to_string(expr.right) + (")" if use_parens else "")
    elif isinstance(expr, Term):
        return (str(expr.left) if expr.left != 1 else "") + "*" + expr_to_string(expr.right, use_spaces=False, use_parens=False)
    elif isinstance(expr, Function):
        return expr.name + "(" + ", ".join([expr_to_string(x, use_parens=False) for x in expr.arguments]) + ")" 
    else:
        raise Exception(expr)