Skip to content

Instantly share code, notes, and snippets.

@sangwon090
Last active November 9, 2019 07:18
Show Gist options
  • Save sangwon090/026d853c6a01e3487689a4f18a9f313d to your computer and use it in GitHub Desktop.
Save sangwon090/026d853c6a01e3487689a4f18a9f313d to your computer and use it in GitHub Desktop.
[Rust] Reverse Polish Notation
use std::io;
fn main() {
'main: loop {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let input = remove_newline(&input);
if input.to_lowercase() == "exit" {
break;
}
let input: Vec<&str> = input.split(' ').collect();
let mut stack: Vec<f64> = Vec::new();
for item in input {
match item {
"+" | "-" | "*" | "/" => {
let number: (f64, f64) = match pop(&mut stack) {
Ok(n) => n,
Err(e) => {
println!("ERROR: {}", e);
continue 'main;
}
};
match item {
"+" => stack.push(number.0 + number.1),
"-" => stack.push(number.0 - number.1),
"*" => stack.push(number.0 * number.1),
"/" => stack.push(number.0 / number.1),
_ => panic!("PANIC: 올바르지 않은 토큰 '{}'이(가) 필터링 되지 않았습니다!", item),
}
},
_ => {
let number: f64 = match item.parse() {
Ok(n) => n,
Err(_) => {
println!("ERROR: '{}'은(는) 올바른 토큰이 아닙니다!", item);
continue 'main;
},
};
stack.push(number);
}
}
}
match stack.pop() {
Some(n) => println!("{}", n),
None => {
println!("ERROR: 출력할 결과가 없습니다!");
}
}
}
}
fn pop(queue: &mut Vec<f64>) -> Result<(f64, f64), &str> {
let a: f64 = match queue.pop() {
Some(n) => n,
None => return Err("계산에 필요한 숫자가 부족합니다!"),
};
let b: f64 = match queue.pop() {
Some(n) => n,
None => return Err("계산에 필요한 숫자가 부족합니다!"),
};
Ok((a, b))
}
fn remove_newline(line: &String) -> &str {
let bytes = line.as_bytes();
for (i, &c) in bytes.iter().enumerate() {
if c == b'\n' {
return &line[..i];
}
}
return &line[..];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment