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
classValue(AST):
...
defeval(self, variables):
returnself.value
Variable
classVariable(AST):
...
defeval(self, variables):
returnvariables[self.name]
FuncCall
classFuncCall(AST):
...
defeval(self, variables):
args= [arg.eval(variables) forarginself.args]
returnvariables[self.name](args)
BinaryOp
classBinaryOp(AST):
...
defeval(self, variables):
left=self.left.eval(variables)
right=self.right.eval(variables)
ifself.op=='+':
returnleft+rightifself.op=='-':
returnleft-rightifself.op=='*':
returnleft*rightifself.op=='/':
returnleft/rightifself.op=='%':
returnleft%right
UnaryOp
classUnaryOp(AST):
...
defeval(self, variables):
item=self.item.eval(variables)
ifself.op=='+':
return+item# redundant, but ey why notifself.op=='-':
return-item

And we are done!

%>py main.py
2.2704074859237844

Back: Nodes Parsing | Chapters | Next: Conclusion