Advertisement
BilakshanP

Rust RPN AST Solver

Jun 18th, 2023
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.08 KB | None | 0 0
  1. fn main() {
  2.     use Token::{Number, Operation, Func as Fx};
  3.     use Operator::{Add, Sub, Mul, Div};
  4.  
  5.     let expression: Vec<Token> = vec![
  6.         Number(2.), Number(3.), Operation(Add),
  7.         Number(9.), Number(8.), Operation(Sub), Operation(Sub),
  8.         Number(4.0_f64.powf(64.0)),
  9.         Fx("log".to_string()), Fx("sqrt".to_string())
  10.     ];
  11.     let evaluated = evaluate(&expression);
  12.     println!("{:?}", evaluated)
  13. }
  14.  
  15. #[derive(Debug)]
  16. enum Operator {
  17.     Add, Sub, Mul, Div
  18. }
  19.  
  20. #[derive(Debug)]
  21. enum Token {
  22.     Number(f64),
  23.     Operation(Operator),
  24.     Func(String),
  25.     Unknown
  26. }
  27.  
  28. fn evaluate(tokens: &[Token]) -> f64 {
  29.     let mut stack: Vec<f64> = Vec::new();
  30.  
  31.     for token in tokens {
  32.         println!("{:?}", stack);
  33.  
  34.         match token {
  35.             Token::Number(num) => stack.push(*num),
  36.             Token::Operation(op) => {
  37.                 let right = stack.pop().unwrap();
  38.                 let left = stack.pop().unwrap();
  39.  
  40.                 stack.push(
  41.                     match op {
  42.                         Operator::Add => left + right,
  43.                         Operator::Sub => left - right,
  44.                         Operator::Mul => left * right,
  45.                         Operator::Div => left / right
  46.                     }
  47.                 )
  48.             },
  49.             Token::Func(function) => {
  50.                 let result = eval_function(function, &mut stack);
  51.                 stack.push(result)
  52.             },
  53.             Token::Unknown => panic!("Unknown encountered")
  54.         }
  55.     }
  56.  
  57.     println!("{:?}", stack);
  58.  
  59.     *stack.last().unwrap()
  60. }
  61.  
  62. fn eval_function(function: &str, stack: &mut Vec<f64>) -> f64 {
  63.     let right = stack.pop().unwrap();
  64.     match function {
  65.         "sin" => right.sin(),
  66.         "cos" => right.cos(),
  67.         "tan" => right.tan(),
  68.         "sqrt" => right.sqrt(),
  69.         "cbrt" => right.cbrt(),
  70.         "ln" => right.ln(),
  71.         "log2" => right.log2(),
  72.         "log10" => right.log10(),
  73.         "log" => right.log(stack.pop().unwrap()),
  74.         _ => panic!("unknown function: {}", function)
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement