From 9994919127468a5bc7b3ad1f364faee4f9188744 Mon Sep 17 00:00:00 2001 From: Jeff Date: Fri, 29 Sep 2023 06:02:46 -0400 Subject: [PATCH] Implement subtraction --- src/interface.rs | 1 + src/value/mod.rs | 51 +++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/interface.rs b/src/interface.rs index d59a4d0..cb9800e 100644 --- a/src/interface.rs +++ b/src/interface.rs @@ -276,6 +276,7 @@ impl Operation { let right = self.right.run(context, &mut cursor, source)?; let result = match self.operator.as_str() { "+" => left + right, + "-" => left - right, "=" => { if let Expression::Identifier(key) = &self.left { context.set_value(key, right)?; diff --git a/src/value/mod.rs b/src/value/mod.rs index 7d96503..e56bc49 100644 --- a/src/value/mod.rs +++ b/src/value/mod.rs @@ -17,7 +17,7 @@ use std::{ convert::TryFrom, fmt::{self, Display, Formatter}, marker::PhantomData, - ops::Add, + ops::{Add, Sub}, }; pub mod function; @@ -256,8 +256,8 @@ impl Value { impl Add for Value { type Output = Result; - fn add(self, right: Self) -> Self::Output { - match (self, right) { + fn add(self, other: Self) -> Self::Output { + match (self, other) { (Value::String(left), Value::String(right)) => { let concatenated = left + &right; @@ -298,6 +298,51 @@ impl Add for Value { } } +impl Sub for Value { + type Output = Result; + + fn sub(self, other: Self) -> Self::Output { + match (&self, &other) { + (Value::String(_), Value::String(_)) => Err(Error::ExpectedNumber { + actual: self.clone(), + }), + (Value::String(_), other) | (other, Value::String(_)) => Err(Error::ExpectedNumber { + actual: other.clone(), + }), + (Value::Float(left), Value::Float(right)) => { + let addition = left - right; + + Ok(Value::Float(addition)) + } + (Value::Float(_), other) | (other, Value::Float(_)) => Err(Error::ExpectedFloat { + actual: other.clone(), + }), + (Value::Integer(left), Value::Integer(right)) => Ok(Value::Integer(left - right)), + (Value::Integer(_), other) | (other, Value::Integer(_)) => Err(Error::ExpectedInt { + actual: other.clone(), + }), + (Value::Boolean(_), Value::Boolean(_)) => todo!(), + (Value::Boolean(_), other) | (other, Value::Boolean(_)) => { + Err(Error::ExpectedBoolean { + actual: other.clone(), + }) + } + (Value::List(_), Value::List(_)) => todo!(), + (Value::List(_), other) | (other, Value::List(_)) => Err(Error::ExpectedList { + actual: other.clone(), + }), + (Value::Map(_), Value::Map(_)) => todo!(), + (Value::Map(_), other) | (other, Value::Map(_)) => Err(Error::ExpectedMap { + actual: other.clone(), + }), + (Value::Empty, Value::Empty) => Ok(Value::Empty), + _ => Err(Error::CustomMessage( + "Cannot add the given types.".to_string(), + )), + } + } +} + impl Eq for Value {} impl PartialOrd for Value {