From a5238794efce5767139d9c4dbdf056bb859921d1 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Fri, 22 Mar 2019 19:26:47 +0530 Subject: support unary operators (minus and plus) --- src/lex/mod.rs | 22 +++++++++++++++++++--- src/main.rs | 2 -- 2 files changed, 19 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/lex/mod.rs b/src/lex/mod.rs index 7fd5e33..47e35b0 100644 --- a/src/lex/mod.rs +++ b/src/lex/mod.rs @@ -71,15 +71,31 @@ pub fn lexer(input: &str) -> Result, String> { } char_vec.push(letter); }, - '+' | '-' | '/' | '*' | '^' => { + '+' | '-' => { + let op_token = match letter { + '+' => Operator::token_from_op('+', |x, y| x + y, 2, true), + '-' => Operator::token_from_op('-', |x, y| x - y, 2, true), + _ => unreachable!() + }; + let parse_num = num_vec.parse::().ok(); + if let Some(x) = parse_num { + result.push(Token::Num(x)); + num_vec.clear(); + result.push(op_token); + } else { + result.push(Token::LParen); + result.push(Token::Num((letter.to_string() + "1").parse::().unwrap())); + result.push(Token::RParen); + result.push(Operator::token_from_op('*', |x, y| x * y, 2, true)); + } + }, + '/' | '*' | '^' => { let parse_num = num_vec.parse::().ok(); if let Some(x) = parse_num { result.push(Token::Num(x)); num_vec.clear(); } let operator_token: Token = match letter { - '+' => Operator::token_from_op('+', |x, y| x + y, 2, true), - '-' => Operator::token_from_op('-', |x, y| x - y, 2, true), '/' => Operator::token_from_op('/', |x, y| x / y, 3, true), '*' => Operator::token_from_op('*', |x, y| x * y, 3, true), '^' => Operator::token_from_op('^', |x, y| x.powf(y), 4, false), diff --git a/src/main.rs b/src/main.rs index 98db219..f3f9d2d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,8 +16,6 @@ fn main() { let input = input.replace(" ", ""); let input = autobalance_parens(&input[..]).unwrap(); - println!("{}", input); - if input == "exit" { return } -- cgit v1.2.3