Building the evaluator
Once the AST
(node tree) is constructed in the parser, evaluating the numeric value from AST
is a straightforward operation. The evaluator function parses each node in the AST
tree recursively and arrives at the final value.
For example, if the AST
node is Add(Number(1.0),Number(2.0)), it evaluates to 3.0.
If the AST
node is Add(Number(1.0),Multiply(Number(2.0),Number(3.0)):
- It evaluates value of Number(1.0) to 1.0.
- Then it evaluates Multiply(Number(2.0), Number(3.0)) to 6.0.
- It then adds 1.0 and 6.0 to get the final value of 7.0.
Let's now look at the code for the eval()
function:
src/parsemath/ast.rs
pub fn eval(expr: Node) -> Result<f64, Box<dyn error::Error>> { use self::Node::*; match expr { Number(i) => Ok(i), Add(expr1, expr2) => Ok(eval(*expr1)? +...