Skip to content

Instantly share code, notes, and snippets.

@randrews
Created August 17, 2021 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save randrews/932032e79d22a34ccd192e36c55db8f8 to your computer and use it in GitHub Desktop.
Save randrews/932032e79d22a34ccd192e36c55db8f8 to your computer and use it in GitHub Desktop.
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