jweinst1
4/17/2017 - 10:33 PM

an enum arithmetic system with rust

an enum arithmetic system with rust

//binary computation tree

//simulates infinite binary tree of pluses using boxes
enum BinComp {
    Int(i32),
    Plus(Box<BinComp>, Box<BinComp>),
    Sub(Box<BinComp>, Box<BinComp>),
    Mul(Box<BinComp>, Box<BinComp>),
    Div(Box<BinComp>, Box<BinComp>),
    Rem(Box<BinComp>, Box<BinComp>)
}

impl BinComp {
    fn call(self) -> i32 {
        match self {
            BinComp::Int(num) => num,
            BinComp::Plus(l, r) => l.call() + r.call(),
            BinComp::Sub(l, r) => l.call() - r.call(),
            BinComp::Mul(l, r) => l.call() * r.call(),
            BinComp::Div(l, r) => l.call() / r.call(),
            BinComp::Rem(l, r) => l.call() % r.call()
        }
    }
}

fn main() {
   let f = BinComp::Mul(Box::new(BinComp::Sub(Box::new(BinComp::Int(8)), Box::new(BinComp::Int(6)))), Box::new(BinComp::Int(6)));
   println!("{}", f.call());
   // (8 - 6) * 6 = 12
}