rust - Ranged Type with ZEN style.

use std::to_str::ToStr;


 #[deriving(Show)]
enum RangedIntLessThen500 {
    OutOfRange,
    RI(int)
}

impl Add<RangedIntLessThen500, RangedIntLessThen500> for RangedIntLessThen500{
    fn add(&self, _rhs: &RangedIntLessThen500) -> RangedIntLessThen500 {
        match (*self, *_rhs) {
                   (RI(x),RI(y)) => {
                       let value = x + y;
                       if value < 500 { RI(value) } else { OutOfRange }
                   },
                   (OutOfRange, _) => OutOfRange,
                   (_, OutOfRange) => OutOfRange
        }
    }
}

impl RangedIntLessThen500 {
     fn from_int(i: int) -> RangedIntLessThen500 {
        if i < 500 { RI(i) } else { OutOfRange }
    }

    fn unwrap(self) -> int {
            match self {
                RI(x) => x,
                OutOfRange => fail!("failed to unwrap RangedIntLessThen500 - OutOfRange!")
            }
    }
}

fn main() {
    let i = RangedIntLessThen500::from_int(1) + RangedIntLessThen500::from_int(300) ;
    let j = RangedIntLessThen500::from_int(201) + RangedIntLessThen500::from_int(300) ;
    let k = RangedIntLessThen500::from_int(500) + RangedIntLessThen500::from_int(-1);
    println!("i: {}", i.to_str());
    println!("j: {}", j.to_str());
    println!("k: {}", k.to_str());
}

Posted on 2014-05-20 02:32 with rust in 0.049 sec.