Skip to content

Instantly share code, notes, and snippets.

@eutampieri
Last active July 9, 2020 20:39
Show Gist options
  • Save eutampieri/7b6c14cb408386e2b8d9d65987426cf8 to your computer and use it in GitHub Desktop.
Save eutampieri/7b6c14cb408386e2b8d9d65987426cf8 to your computer and use it in GitHub Desktop.
use std::default::Default;
use std::ops::{Add, Div, Mul, Sub};
use std::rc::Rc;
enum Value<
T: Add<Output = T> + Mul<Output = T> + Div<Output = T> + Sub<Output = T> + Copy + Default,
> {
Times,
Plus,
Minus,
Divide,
Number(T),
}
struct Node<
T: Add<Output = T> + Mul<Output = T> + Div<Output = T> + Sub<Output = T> + Copy + Default,
> {
left: Option<Rc<Node<T>>>,
right: Option<Rc<Node<T>>>,
value: Value<T>,
}
fn calc<
T: Add<Output = T> + Mul<Output = T> + Div<Output = T> + Sub<Output = T> + Copy + Default,
>(
node: &Node<T>,
) -> T {
if node.left.is_none() && node.right.is_none() {
match node.value {
Value::Number(n) => n,
_ => T::default(),
}
} else {
match node.value {
Value::Number(n) => n,
Value::Times => calc(node.left.as_ref().unwrap()) * calc(node.right.as_ref().unwrap()),
Value::Plus => calc(node.left.as_ref().unwrap()) + calc(node.right.as_ref().unwrap()),
Value::Divide => calc(node.left.as_ref().unwrap()) / calc(node.right.as_ref().unwrap()),
Value::Minus => calc(node.left.as_ref().unwrap()) - calc(node.right.as_ref().unwrap()),
}
}
}
fn main() {
let tree_root: Node<i8> = Node {
value: Value::Times,
left: Some(Rc::new(Node {
value: Value::Plus,
left: Some(Rc::new(Node {
value: Value::Number(1),
left: None,
right: None,
})),
right: Some(Rc::new(Node {
value: Value::Minus,
left: Some(Rc::new(Node {
value: Value::Number(8),
left: None,
right: None,
})),
right: Some(Rc::new(Node {
value: Value::Number(4),
left: None,
right: None,
})),
})),
})),
right: Some(Rc::new(Node {
value: Value::Number(18),
left: None,
right: None,
})),
};
println!("Output = {}", calc(&tree_root));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment