exercises

Log | Files | Refs | README

operator.rs (1452B)


      1 use crate::{OperatorToken, token::Function};
      2 
      3 #[derive(Debug, Clone, PartialEq)]
      4 pub enum Operator {
      5     Add,
      6     Subtract,
      7     Multiply,
      8     Divide,
      9     Power,
     10     Root,
     11     Factorial,
     12 }
     13 
     14 #[derive(Clone)]
     15 pub struct StandardOperator(pub Operator);
     16 
     17 impl OperatorToken for StandardOperator {
     18     fn precedence(&self) -> u8 {
     19         match self.0 {
     20             Operator::Add | Operator::Subtract => 1,
     21             Operator::Multiply | Operator::Divide => 2,
     22             Operator::Power => 3,
     23             Operator::Root | Operator::Factorial => 4,
     24         }
     25     }
     26 
     27     fn evaluate(&self, args: &[f64]) -> Result<f64, String> {
     28         match self.0 {
     29             Operator::Add => Ok(args[0] + args[1]),
     30             Operator::Subtract => Ok(args[0] - args[1]),
     31             Operator::Multiply => Ok(args[0] * args[1]),
     32             Operator::Divide => {
     33                 if args[1] == 0.0 {
     34                     Err("Division by zero".to_string())
     35                 } else {
     36                     Ok(args[0] / args[1])
     37                 }
     38             }
     39             // ... other operators
     40             _ => Err("Operation not supported in standard mode".to_string()),
     41         }
     42     }
     43 }
     44 
     45 #[derive(Clone)]
     46 pub enum ScientificOperator {
     47     Basic(Operator),
     48     Function(Function),
     49 }
     50 
     51 impl OperatorToken for ScientificOperator {
     52     fn precedence(&self) -> u8 {
     53         todo!()
     54     }
     55 
     56     fn evaluate(&self, args: &[f64]) -> Result<f64, String> {
     57         todo!()
     58     }
     59 }