Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- fn main() {
- use Token::{Number, Operation, Func as Fx};
- use Operator::{Add, Sub, Mul, Div};
- let expression: Vec<Token> = vec![
- Number(2.), Number(3.), Operation(Add),
- Number(9.), Number(8.), Operation(Sub), Operation(Sub),
- Number(4.0_f64.powf(64.0)),
- Fx("log".to_string()), Fx("sqrt".to_string())
- ];
- let evaluated = evaluate(&expression);
- println!("{:?}", evaluated)
- }
- #[derive(Debug)]
- enum Operator {
- Add, Sub, Mul, Div
- }
- #[derive(Debug)]
- enum Token {
- Number(f64),
- Operation(Operator),
- Func(String),
- Unknown
- }
- fn evaluate(tokens: &[Token]) -> f64 {
- let mut stack: Vec<f64> = Vec::new();
- for token in tokens {
- println!("{:?}", stack);
- match token {
- Token::Number(num) => stack.push(*num),
- Token::Operation(op) => {
- let right = stack.pop().unwrap();
- let left = stack.pop().unwrap();
- stack.push(
- match op {
- Operator::Add => left + right,
- Operator::Sub => left - right,
- Operator::Mul => left * right,
- Operator::Div => left / right
- }
- )
- },
- Token::Func(function) => {
- let result = eval_function(function, &mut stack);
- stack.push(result)
- },
- Token::Unknown => panic!("Unknown encountered")
- }
- }
- println!("{:?}", stack);
- *stack.last().unwrap()
- }
- fn eval_function(function: &str, stack: &mut Vec<f64>) -> f64 {
- let right = stack.pop().unwrap();
- match function {
- "sin" => right.sin(),
- "cos" => right.cos(),
- "tan" => right.tan(),
- "sqrt" => right.sqrt(),
- "cbrt" => right.cbrt(),
- "ln" => right.ln(),
- "log2" => right.log2(),
- "log10" => right.log10(),
- "log" => right.log(stack.pop().unwrap()),
- _ => panic!("unknown function: {}", function)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement