Skip to content

Instantly share code, notes, and snippets.

@jesperdj
Created June 29, 2020 08:01
Show Gist options
  • Save jesperdj/cd832f0e6bc3bf0a4722b6e2f8592bc1 to your computer and use it in GitHub Desktop.
Save jesperdj/cd832f0e6bc3bf0a4722b6e2f8592bc1 to your computer and use it in GitHub Desktop.
Algebraic data types: enums in Rust - expression evaluator
use std::collections::HashMap;
use Expression::*;
#[derive(Debug)]
enum Expression<'a> {
Literal(f64),
Variable(String),
Add(&'a Expression<'a>, &'a Expression<'a>),
Subtract(&'a Expression<'a>, &'a Expression<'a>),
Multiply(&'a Expression<'a>, &'a Expression<'a>),
Divide(&'a Expression<'a>, &'a Expression<'a>),
}
fn evaluate(expr: &Expression, variables: &HashMap<String, f64>) -> f64 {
match expr {
Literal(value) => *value,
Variable(name) => *variables.get(name).unwrap(),
Add(left, right) => evaluate(left, variables) + evaluate(right, variables),
Subtract(left, right) => evaluate(left, variables) + evaluate(right, variables),
Multiply(left, right) => evaluate(left, variables) + evaluate(right, variables),
Divide(left, right) => evaluate(left, variables) + evaluate(right, variables),
}
}
fn main() {
// 1 + (2 - 3 / 4) * x
// Terminals
let one = Literal(1.0);
let two = Literal(2.0);
let three = Literal(3.0);
let four = Literal(4.0);
let x = Variable(String::from("x"));
// Non-terminals
let div = Divide(&three, &four);
let sub = Subtract(&two, &div);
let mul = Multiply(&sub, &x);
let expr = Add(&one, &mul);
println!("expr = {:?}", expr);
let mut variables = HashMap::new();
variables.insert(String::from("x"), 2.5);
println!("variables = {:?}", variables);
let result = evaluate(&expr, &variables);
println!("result = {}", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment