Tiny Interpreter Part 3 of 3

Tiny Interpreter:
Evaluating

The last part walks the tree. This time in Rust, to show another language in the code theme.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
fn eval(node: &Node) -> f64 {
    match node {
        Node::Number(n) => *n,
        Node::Binary(op, l, r) => {
            let (a, b) = (eval(l), eval(r));
            match op {
                '+' => a + b,
                '-' => a - b,
                '*' => a * b,
                _ => a / b,
            }
        }
    }
}

One evaluation, step by step

sequenceDiagram
  participant R as REPL
  participant P as Parser
  participant E as Evaluator
  R->>P: "1 + 2 * 3"
  P-->>R: tree
  R->>E: eval(tree)
  E-->>R: 7