Created
August 17, 2021 00:59
-
-
Save randrews/932032e79d22a34ccd192e36c55db8f8 to your computer and use it in GitHub Desktop.
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
use std::io; | |
struct Stack(Vec<f32>); | |
fn main() -> io::Result<()> { | |
let stdin = io::stdin(); | |
let mut stack = Stack::new(); | |
let mut line = String::new(); | |
'quit: loop { | |
line.clear(); | |
stdin.read_line(&mut line)?; | |
for word in line.split(char::is_whitespace) { | |
if let Ok(num) = word.parse::<f32>() { | |
stack.push(num); | |
} else { | |
match word { | |
"" => continue, | |
"exit" => break 'quit, | |
"+" => stack.apply(|a, b| a + b), | |
"-" => stack.apply(|a, b| a - b), | |
"/" => stack.apply(|a, b| a / b), | |
"*" => stack.apply(|a, b| a * b), | |
"%" => stack.apply(|a, b| a % b), | |
"." => println!("{}", stack.pop()), | |
_ => println!("? {}", word) | |
} | |
} | |
} | |
} | |
println!("Bye!"); | |
Ok(()) | |
} | |
impl Stack { | |
fn new() -> Self { Self(Vec::new()) } | |
fn push(&mut self, val: f32) { | |
self.0.push(val); | |
} | |
fn pop(&mut self) -> f32 { | |
return self.0.pop().expect("Stack underflow"); | |
} | |
fn apply<F: Fn(f32, f32) -> f32>(&mut self, op: F) { | |
let b = self.0.pop().expect("Stack underflow"); | |
let a = self.0.pop().expect("Stack underflow"); | |
self.0.push(op(a, b)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment