Implement subtraction

This commit is contained in:
Tiffany Bennett 2016-08-07 22:46:36 -04:00
parent ec09c3a48c
commit fb32b61518
2 changed files with 19 additions and 2 deletions

View file

@ -433,6 +433,17 @@ impl Context {
(Err(e), _) => Err(e),
(_, Err(e)) => Err(e),
},
Expr::Sub(ref top, ref bottom) => match (self.eval(&**top), self.eval(&**bottom)) {
(Ok(top), Ok(mut bottom)) => {
bottom.0 = -bottom.0;
top.add(&bottom).ok_or_else(|| {
format!("Sub of values with differing units is not meaningful: {} - {}",
self.show(&top), self.show(&bottom))
})
},
(Err(e), _) => Err(e),
(_, Err(e)) => Err(e),
},
Expr::Mul(ref args) => args.iter().fold(Ok(Value::new(one())), |a, b| {
a.and_then(|a| {
let b = try!(self.eval(b));
@ -506,7 +517,7 @@ impl Context {
})
.collect::<BTreeMap<_, _>>())
},
Expr::Add(ref left, ref right) => {
Expr::Add(ref left, ref right) | Expr::Sub(ref left, ref right) => {
let left = try!(self.eval_unit_name(left));
let right = try!(self.eval_unit_name(right));
if left != right {

View file

@ -239,6 +239,7 @@ pub enum Expr {
Mul(Vec<Expr>),
Pow(Box<Expr>, Box<Expr>),
Add(Box<Expr>, Box<Expr>),
Sub(Box<Expr>, Box<Expr>),
Neg(Box<Expr>),
Plus(Box<Expr>),
Convert(Box<Expr>, Box<Expr>),
@ -294,7 +295,7 @@ fn parse_pow(mut iter: &mut Iter) -> Expr {
fn parse_mul(mut iter: &mut Iter) -> Expr {
let mut terms = vec![parse_pow(iter)];
loop { match *iter.peek().unwrap() {
Token::Plus | Token::DashArrow | Token::TriplePipe | Token::RPar | Token::Newline |
Token::Plus | Token::Minus | Token::DashArrow | Token::TriplePipe | Token::RPar | Token::Newline |
Token::Comment(_) | Token::Eof => break,
Token::Slash => {
iter.next();
@ -326,6 +327,11 @@ fn parse_add(mut iter: &mut Iter) -> Expr {
let right = parse_add(iter);
Expr::Add(Box::new(left), Box::new(right))
},
Token::Minus => {
iter.next();
let right = parse_add(iter);
Expr::Sub(Box::new(left), Box::new(right))
},
_ => left
}
}