add square root function

This commit is contained in:
2024-04-14 15:45:24 +02:00
parent e59d23d26d
commit 7ea94f9cef

View File

@@ -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<Token, TokenizeError> {
"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<Token>) -> Result<f64, CalculateError> {
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.);
}
}