diff --git a/src/calc.rs b/src/calc.rs index c8bea0c..6fef4f1 100644 --- a/src/calc.rs +++ b/src/calc.rs @@ -1,7 +1,7 @@ use std::io::Error; #[derive(Clone)] -struct CalcNode { +pub struct CalcNode { item: Item, left: Option>, right: Option>, @@ -35,9 +35,17 @@ impl CalcTree { } pub fn insert(&mut self, item: Item) { use Item::*; - if let Oper(_) = item { + if let Oper(operation) = &item { match &self.root.item { - Num(_) => self.root = CalcNode::new(item, Some(Box::new(self.root.clone())), None), + Num(_) => { + if matches!(*operation, Operation::Div) || matches!(*operation, Operation::Mult) + { + let inserted = CalcNode::new(item, self.root.right.clone(), None); + self.root.right = Some(Box::new(inserted)); + } else { + self.root = CalcNode::new(item, Some(Box::new(self.root.clone())), None); + } + } Oper(_) => panic!("fuck off"), } } else { @@ -55,4 +63,39 @@ impl CalcTree { } } } + pub fn resolve(root: &CalcNode) -> Item { + use Item::*; + if let Oper(operation) = &root.item { + let mut a: i32 = 0; + let mut b: i32 = 0; + if let Some(node) = &root.left { + match node.item { + Num(value) => a = value, + Oper(_) => { + if let Num(value) = CalcTree::resolve(&node) { + a = value + } + } + } + } + if let Some(node) = &root.right { + match node.item { + Num(value) => b = value, + Oper(_) => { + if let Num(value) = CalcTree::resolve(&node) { + b = value + } + } + } + } + match operation { + Operation::Add => Num(a + b), + Operation::Sub => Num(a - b), + Operation::Div => Num(a / b), + Operation::Mult => Num(a * b), + } + } else { + root.item.clone() + } + } }