Arithmetic Expression Evaluator
unknown
rust
a year ago
1.2 kB
13
Indexable
enum Operation {
Add,
Sub,
Mul,
Div,
}
enum Expression {
Number(i32),
Operation(Box<Expression>, Operation, Box<Expression>),
}
fn operation(left: i32, op: &Operation, right: i32) -> i32 {
match op {
Operation::Add => left + right,
Operation::Sub => left - right,
Operation::Mul => left * right,
Operation::Div => left / right,
}
}
fn evaluate(expression: &Expression) -> i32 {
match expression {
Expression::Number(n) => *n,
Expression::Operation(left, op, right) => operation(evaluate(left), op, evaluate(right))
}
}
fn operation_res(left: i32, op: &Operation, right: i32) -> Result<i32, String> {
match op {
Operation::Add => Ok(left + right),
Operation::Sub => Ok(left - right),
Operation::Mul => Ok(left * right),
Operation::Div => if right != 0 { Ok(left / right) } else { Err("Division By Zero".to_string()) },
}
}
fn evaluate_res(expression: &Expression) -> Result<i32, String> {
match expression {
Expression::Number(n) => Ok(*n),
Expression::Operation(left, op, right) => operation_res(evaluate_res(left)?, op, evaluate_res(right)?)
}
}Editor is loading...
Leave a Comment