exercises

Log | Files | Refs | README

token.rs (1154B)


      1 use std::borrow::Cow;
      2 
      3 /// Instead of using class hierarchy with factory methods for each type, in Rust
      4 /// we can take a more natural approach, using enums (which provide sum type
      5 /// functionality)
      6 ///
      7 /// The Token enum is now generic over Number and Operator types to support
      8 /// different factory implementations.
      9 #[derive(Debug, Clone, PartialEq)]
     10 pub enum Token<N, O> {
     11     Number(N),
     12     Operator(O),
     13     Function(Function),
     14     Variable(String),
     15     OpenParen,
     16     CloseParen,
     17 }
     18 
     19 #[derive(Debug, Clone, PartialEq)]
     20 pub enum Function {
     21     Sqrt,
     22     Sin,
     23     Cos,
     24     Tan,
     25 }
     26 
     27 /// Constructors for the different Token enum types
     28 impl<N, O> Token<N, O> {
     29     pub fn function(func: Function) -> Self {
     30         Self::Function(func)
     31     }
     32 
     33     pub fn variable(name: impl Into<String>) -> Self {
     34         Self::Variable(name.into())
     35     }
     36 }
     37 
     38 /// Using Cow for Strings and Slices - Prototype Pattern
     39 pub struct VariableToken<'a> {
     40     name: Cow<'a, str>,
     41     value: f64,
     42 }
     43 
     44 impl<'a> VariableToken<'a> {
     45     pub fn new(name: impl Into<Cow<'a, str>>, value: f64) -> Self {
     46         Self {
     47             name: name.into(),
     48             value,
     49         }
     50     }
     51 }