Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds support for exponential notation #80

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion src/lex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,10 +263,27 @@ pub(crate) fn lexer(input: &str, prev_ans: Option<f64>) -> Result<Vec<Token>, Ca
}
'a'..='z' | 'A'..='Z' => {
let parse_num = num_vec.parse::<f64>().ok();

if let Some(x) = parse_num {
num_vec.clear();

// Check for exponential notation
if letter == 'e' {
while let Some(next) = chars.next_if(|&x| matches!(x, '0'..='9')) {
num_vec.push(next);
}

if !num_vec.is_empty() {
if let Some(exp) = num_vec.parse::<usize>().ok() {
result.push(Token::Num(x * num::pow(10 as f64, exp) as f64));
num_vec.clear();
continue;
}
}
}

result.push(Token::Num(x));
result.push(OPERATORS.get(&'*').unwrap().clone());
num_vec.clear();
}
char_vec.push(letter);
last_char_is_op = false;
Expand Down
11 changes: 11 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,17 @@ mod tests {
let evaled = eval("exp(3)", None);
assert_eq!(evaled, Ok(20.0855369232));
}
#[test]
fn eval_exponential_notation() {
let evaled = eval("1e11", None);
assert_eq!(evaled, Ok(100000000000.0));
}
#[test]
fn eval_exponential_notation_decimal() {
let evaled = eval("2.5e5", None);
assert_eq!(evaled, Ok(250000.0));
}

#[test]
fn eval_e_times_n() {
let evaled = eval("e0", None);
Expand Down