From 7375d87ea553bc318b224909544dbda470de73ca Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Tue, 19 Mar 2019 22:02:45 +0530 Subject: add lexed to rpn function --- src/main.rs | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index c91b662..d9f6b01 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,7 +6,7 @@ pub struct Operator { is_left_associative: bool, } -#[derive(Debug)] +#[derive(Debug, Copy, Clone)] pub enum Token { Operator(Operator), Num(f64), @@ -31,11 +31,11 @@ impl Operator { } fn main() { - let input = "1(2)"; + let input = "1 + 2 * 3"; let input = input.replace(" ", ""); let lexed = lexer(&input); - println!("{:?}", lexed); - println!("{}", lexed.unwrap().len()); + let postfixed = to_postfix(lexed.unwrap()); + println!("{:?}", postfixed); } fn lexer(input: &str) -> Result, String> { @@ -93,3 +93,65 @@ fn lexer(input: &str) -> Result, String> { } Ok(result) } + +fn to_postfix(tokens: Vec) -> Result, String> { + let mut postfixed: Vec = vec![]; + let mut op_stack: Vec = vec![]; + for token in tokens { + match token { + Token::Num(_) => { + postfixed.push(token); + println!("pushed a number {:?}", token); + }, + Token::Operator(current_op) => { + while let Some(top_op) = op_stack.last() { + match top_op { + Token::LParen => { + return Err(format!("Mismatched Parentheses!")) + } + Token::Operator(top_op) => { + let tp = top_op.precedence; + let cp = current_op.precedence; + if tp > cp || (tp == cp && top_op.is_left_associative) { + postfixed.push(op_stack.pop().unwrap()); + println!("pushed an operator special {:?}", token); + } else { + break; + } + } + _ => { + return Err(format!("Unexpected match branch part 2")) + } + } + } + op_stack.push(token); + println!("pushed an operator {:?}", token); + }, + Token::LParen => { + op_stack.push(token); + }, + Token::RParen => { + let mut found: bool = false; + while let Some(top_op) = op_stack.last() { + match top_op { + Token::LParen => { + let _ = op_stack.pop().unwrap(); + found = true; + }, + _ => { + postfixed.push(op_stack.pop().unwrap()); + } + } + } + if found == false { + return Err(format!("Mismatched parentheses part 2")) + } + } + + } + } + while let Some(op) = op_stack.pop() { + postfixed.push(op); + } + Ok(postfixed) +} -- cgit v1.2.3