fn main() { let mut stack = vec![]; // Reverse Polish Notation let str = "100 5 - { 1 2 + } +".to_string(); let mut words: Vec<_> = str.split(" ").collect(); while let Some((&word, mut rest)) = words.split_first() { if word.is_empty() { break; } if word == "{" { let value; (value, rest) = parse_block(rest); stack.push(value); } else if let Ok(parsed) = word.parse::<i32>() { stack.push(parsed); } else { match word { "+" => add(&mut stack), "-" => sub(&mut stack), "*" => mul(&mut stack), "/" => div(&mut stack), _ => panic!("{word:?} could not be parsed"), } } words = rest.to_vec(); } println!("{:?}", stack); } fn parse_block<'src, 'a>(input: &'a [&'src str]) -> (i32, &'a [&'src str]){ let mut tokens: Vec<i32> = vec![]; let mut words = input; while let Some((&word, mut rest)) = words.split_first() { if word.is_empty() { break; } if word == "}" { return (tokens[0], rest); } else if let Ok(parsed) = word.parse::<i32>() { tokens.push(parsed); } else { match word { "+" => add(&mut tokens), "-" => sub(&mut tokens), "*" => mul(&mut tokens), "/" => div(&mut tokens), _ => todo!(), // _ => panic!("{word:?} could not be parsed"), } } words = rest; } (tokens[0], words) } fn add(stack: &mut Vec<i32>) { let rhs = stack.pop().unwrap(); let lhs = stack.pop().unwrap(); stack.push(lhs + rhs); } fn sub(stack: &mut Vec<i32>) { let rhs = stack.pop().unwrap(); let lhs = stack.pop().unwrap(); stack.push(lhs - rhs); } fn mul(stack: &mut Vec<i32>) { let rhs = stack.pop().unwrap(); let lhs = stack.pop().unwrap(); stack.push(lhs * rhs); } fn div(stack: &mut Vec<i32>) { let rhs = stack.pop().unwrap(); let lhs = stack.pop().unwrap(); stack.push(lhs / rhs); }
[98]