From 7ea94f9cef0e04219f57600b3b82a2186244420f Mon Sep 17 00:00:00 2001 From: Vegard Matthey Date: Sun, 14 Apr 2024 15:45:24 +0200 Subject: [PATCH] add square root function --- src/main.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 528b705..1c73629 100644 --- a/src/main.rs +++ b/src/main.rs @@ -45,6 +45,7 @@ enum FunctionType { NaturalLog, Max, Min, + SquareRoot, } fn main() { @@ -151,6 +152,7 @@ impl std::fmt::Display for Token { FunctionType::NaturalLog => write!(f, "ln"), FunctionType::Max => write!(f, "max"), FunctionType::Min => write!(f, "min"), + FunctionType::SquareRoot => write!(f, "sqrt"), }, } } @@ -223,6 +225,7 @@ fn parse_buffer(buf: &str) -> Result { "ln" => Ok(Token::Function(FunctionType::NaturalLog)), "max" => Ok(Token::Function(FunctionType::Max)), "min" => Ok(Token::Function(FunctionType::Min)), + "sqrt" => Ok(Token::Function(FunctionType::SquareRoot)), _ => { if let Ok(number) = buf.parse() { Ok(Token::Number(number)) @@ -425,7 +428,7 @@ fn calculate(tokens: Vec) -> Result { FunctionType::Sine => Some(n.sin()), FunctionType::Cosine => Some(n.cos()), FunctionType::NaturalLog => Some(n.ln()), - + FunctionType::SquareRoot => Some(n.sqrt()), _ => None, }; if let Some(n) = n { @@ -494,6 +497,10 @@ mod tests { tokenize("cos"), Ok(vec![Token::Function(FunctionType::Cosine)]) ); + assert_eq!( + tokenize("sqrt"), + Ok(vec![Token::Function(FunctionType::SquareRoot)]) + ); assert_eq!( tokenize("3.14159265358979323"), Ok(vec![Token::Number(3.14159265358979323)]) @@ -748,5 +755,6 @@ mod tests { assert_eq!(compute("3sin(3)"), 3. * 3_f64.sin()); assert_eq!(compute("(1 + 2) - (1)"), 2.); assert_eq!(compute("(1 + 2) - 1"), 2.); + assert_eq!(compute("sqrt(4)"), 2.); } }