Skip to content

Latest commit

 

History

History
92 lines (74 loc) · 1.73 KB

File metadata and controls

92 lines (74 loc) · 1.73 KB

Evaluation

Back: Nodes Parsing | Chapters | Next: Conclusion


Add a method def eval(self, variables) to every AST node and recursively call eval until you reach the terminal leaves.

For now we will disregard all runtime errors.

Value
class Value(AST):
    ...
    def eval(self, variables):
        return self.value
Variable
class Variable(AST):
    ...
    def eval(self, variables):
        return variables[self.name]
FuncCall
class FuncCall(AST):
    ...
    def eval(self, variables):
        args = [arg.eval(variables) for arg in self.args]
        return variables[self.name](args)
BinaryOp
class BinaryOp(AST):
    ...
    def eval(self, variables):
        left = self.left.eval(variables)
        right = self.right.eval(variables)
        if self.op == '+':
            return left + right
        if self.op == '-':
            return left - right
        if self.op == '*':
            return left * right
        if self.op == '/':
            return left / right
        if self.op == '%':
            return left % right
UnaryOp
class UnaryOp(AST):
    ...
    def eval(self, variables):
        item = self.item.eval(variables)
        if self.op == '+':
            return +item # redundant, but ey why not
        if self.op == '-':
            return -item

And we are done!

%>py main.py
2.2704074859237844

Back: Nodes Parsing | Chapters | Next: Conclusion