Accept ** operator as exponentiation (#39)

* Accept `**` operator as exponentiation

* Add test of exponentiation
This commit is contained in:
David Tolnay 2020-10-11 21:37:15 -07:00 committed by GitHub
parent ff3ac137ed
commit 7118506a2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 1 deletions

View File

@ -129,7 +129,8 @@ pub fn lexer(input: &str, prev_ans: Option<f64>) -> Result<Vec<Token>, CalcError
let mut result: Vec<Token> = vec![];
let mut last_char_is_op = true;
for letter in input.chars() {
let mut chars = input.chars().peekable();
while let Some(mut letter) = chars.next() {
match letter {
'0'..='9' | '.' => {
if !char_vec.is_empty() {
@ -209,6 +210,11 @@ pub fn lexer(input: &str, prev_ans: Option<f64>) -> Result<Vec<Token>, CalcError
}
'/' | '*' | '%' | '^' | '!' => {
drain_stack(&mut num_vec, &mut char_vec, &mut result);
if letter == '*' && chars.peek() == Some(&'*') {
// Accept `**` operator as meaning `^` (exponentation).
let _ = chars.next();
letter = '^';
}
let operator_token: Token = OPERATORS.get(&letter).unwrap().clone();
result.push(operator_token);
last_char_is_op = true;

View File

@ -227,6 +227,11 @@ mod tests {
assert_eq!(32., evaled);
}
#[test]
fn exponentiation() {
let evaled = eval_math_expression("2 ** 2 ** 3", None).unwrap();
assert_eq!(256., evaled); // 2^(2^3), not (2^2)^3
}
#[test]
fn floating_ops() {
let evaled = eval_math_expression("1.2816 + 1 + 1.2816/1.2", Some(0f64)).unwrap();
assert_eq!(3.3496, evaled);