Created
April 2, 2016 20:31
-
-
Save anonymous/9b0b3feca6676ae776c684e6f7665571 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ParseState { | |
stack: Vec<u64>, | |
num: Option<u64> | |
} | |
fn flush_state(state: &mut ParseState) { | |
match state.num { | |
Some(x) => state.stack.push(x), | |
None => {} | |
} | |
state.num = None; | |
} | |
fn process_char(state: &mut ParseState, c: char) { | |
if c.is_digit(10) { | |
match state.num { | |
Some(x) => state.num = Some(x * 10 + c.to_digit(10).unwrap() as u64), | |
None => state.num = Some(c.to_digit(10).unwrap() as u64) | |
} | |
} else { | |
flush_state(state); | |
match c { | |
'+' => { | |
let val = state.stack.pop().unwrap() + state.stack.pop().unwrap(); | |
state.stack.push(val); | |
}, | |
'-' => { | |
let val = state.stack.pop().unwrap() - state.stack.pop().unwrap(); | |
state.stack.push(val); | |
}, | |
'.' => println!("{}", state.stack.pop().unwrap()), | |
' ' => {} | |
_ => panic!("Invalid input") | |
} | |
} | |
} | |
fn main() { | |
let mut state = ParseState { | |
stack: vec![], | |
num: None | |
}; | |
let input = "1 2 3 + + ."; | |
for c in input.chars() { | |
process_char(&mut state, c); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment