-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathruntime.rs
24 lines (23 loc) · 864 Bytes
/
runtime.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
use crate::parser::{BinaryOperation, Expression, UnaryOperation};
/// Recursively evaluates an expression
pub fn evaluate(expr: Expression) -> f64 {
match expr {
// Binary expressions
Expression::Binary {
operation,
lhs,
rhs,
} => match operation {
BinaryOperation::Addition => evaluate(*lhs) + evaluate(*rhs),
BinaryOperation::Subtraction => evaluate(*lhs) - evaluate(*rhs),
BinaryOperation::Multiplication => evaluate(*lhs) * evaluate(*rhs),
BinaryOperation::Division => evaluate(*lhs) / evaluate(*rhs),
},
// Unary expressions
Expression::Unary { operation, operand } => match operation {
UnaryOperation::Negation => -evaluate(*operand),
},
// Atoms
Expression::Atom(num) => num,
}
}