early calculation

This commit is contained in:
Christoph J. Scherr 2023-02-14 18:47:06 +01:00
parent a3078cf1c1
commit 37e29f17f0
1 changed files with 75 additions and 7 deletions

View File

@ -128,7 +128,7 @@ pub fn form_reverse_polish_notation(regular_math: &str) -> Result<Vec<String>, S
dbg!(&operator_stack);
let o2 = match Operator::get_operator(*(operator_stack.clone().last().clone().unwrap())) {
Some(valid_op) => valid_op,
None => {panic!("Operator '{}' not found.", token);},
None => {panic!("Operator '{}' not found.", token);},
};
// and
// (o2 has greater precedence than o1 or (o1 and o2 have the same precedence and o1
@ -140,7 +140,7 @@ pub fn form_reverse_polish_notation(regular_math: &str) -> Result<Vec<String>, S
let my_c = match operator_stack.pop() {
Some(c) => c,
None => {panic!("weirdly gone!")},
};
};
output_queue.push(vec![my_c]);
}
}
@ -149,10 +149,10 @@ pub fn form_reverse_polish_notation(regular_math: &str) -> Result<Vec<String>, S
/*
// Unnessecary, will be processed by the expression parser
else if '(' == token {
println!("(");
println!("(");
}
else if ')' == token {
println!(")");
println!(")");
}
*/
else {
@ -180,5 +180,73 @@ pub fn form_reverse_polish_notation(regular_math: &str) -> Result<Vec<String>, S
// after we have the rpn, we may want to calculate the values with it.
pub fn calc_reverse_polish_notation(rpn: Vec<String>) -> Result<f64, String> {
Ok(0.0)
// # function to evaluate reverse polish notation
// def evaluate(expression):
// # splitting expression at whitespaces
// expression = expression.split()
// # stack
// stack = []
// # iterating expression
// for ele in expression:
// # ele is a number
// if ele not in '/*+-':
// stack.append(int(ele))
// # ele is an operator
// else:
// # getting operands
// right = stack.pop()
// left = stack.pop()
// # performing operation according to operator
// if ele == '+':
// stack.append(left + right)
// elif ele == '-':
// stack.append(left - right)
// elif ele == '*':
// stack.append(left * right)
// elif ele == '/':
// stack.append(int(left / right))
// # return final answer.
// return stack.pop()
let mut stack: Vec<f64> = Vec::new();
for group in rpn {
dbg!(&group);
// find out what the group is, an operator, a number, or a variable.
// TODO add variables
if (!Operator::is_operator(group.chars().last().unwrap())) {
let possible_num = group.parse::<f64>();
match possible_num {
Ok(valid) => {stack.push(valid);},
Err(_whatever) => {
eprint!("weird error happened, ending process...");
std::process::exit(2);
},
}
dbg!(&stack);
}
else {
let op: Operator = Operator::get_operator(group.chars().last().unwrap()).unwrap();
let right = stack.pop().unwrap();
let left = stack.pop().unwrap();
if op == ADDITION {
stack.push(right + left);
}
else {
todo!();
}
}
}
if stack.is_empty() {
return Err("result stack empty".to_string());
}
if stack.len() > 1 {
dbg!(stack);
return Err("result stack has too many results.".to_string());
}
return Ok(stack[0]);
}