1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use std::collections::VecDeque;
use CalcType::{Add, Divide, Multiply, Power, Print, Subtract, Val};
#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
pub enum CalcType {
Add,
Subtract,
Multiply,
Divide,
Power,
Print,
Val(f64),
}
pub fn str_to_calc_type(string: &str) -> Option<CalcType> {
let as_int = string.parse::<f64>();
let result = match as_int {
Ok(x) => Some(Val(x)),
Err(_) => None,
};
if result.is_some() {
return result;
}
match string {
"+" => Some(Add),
"-" => Some(Subtract),
"*" => Some(Multiply),
"/" => Some(Divide),
"^" => Some(Power),
"p" => Some(Print),
_ => None,
}
}
pub fn eval(input: &str, stack: &mut VecDeque<f64>) {
let toks = input.split(' ').collect::<Vec<&str>>();
let mut ops: VecDeque<CalcType> = VecDeque::new();
for tok in &toks {
let x: CalcType = str_to_calc_type(tok).unwrap();
match x {
Add | Divide | Multiply | Power | Subtract | Print => ops.push_back(x),
Val(x_) => stack.push_back(x_),
}
}
for op in &ops {
match op {
Add => {
let y = &stack.pop_back().unwrap_or(0.0);
let x = &stack.pop_back().unwrap_or(0.0);
&stack.push_back(x + y)
}
Subtract => {
let y = &stack.pop_back().unwrap_or(0.0);
let x = &stack.pop_back().unwrap_or(0.0);
&stack.push_back(x - y)
}
Multiply => {
let y = &stack.pop_back().unwrap_or(0.0);
let x = &stack.pop_back().unwrap_or(0.0);
&stack.push_back(x * y)
}
Divide => {
let y = &stack.pop_back().unwrap_or(0.0);
let x = &stack.pop_back().unwrap_or(0.0);
&stack.push_back(x / y)
}
Power => {
let y = &stack.pop_back().unwrap_or(0.0);
let x = &stack.pop_back().unwrap_or(0.0);
let result = x.powf(*y);
&stack.push_back(result)
}
Print => &{ println!("{:#?}", stack.iter().last()) },
Val(_) => panic!("Unexpected value in the operator stack!"),
};
}
println!("{}", stack.iter().last().unwrap_or(&0.0));
}