typestar

rpn.rs in Rust

Evaluate a reverse-Polish expression with a Vec stack.

use std::env;

fn eval(expr: &str) -> Option<f64> {
    let mut stack: Vec<f64> = Vec::new();
    for token in expr.split_whitespace() {
        match token {
            "+" | "-" | "*" | "/" => {
                let b = stack.pop()?;
                let a = stack.pop()?;
                stack.push(match token {
                    "+" => a + b,
                    "-" => a - b,
                    "*" => a * b,
                    _ => a / b,
                });
            }
            num => stack.push(num.parse().ok()?),
        }
    }
    stack.pop()
}

fn main() {
    let expr: String = env::args().skip(1).collect::<Vec<_>>().join(" ");
    match eval(&expr) {
        Some(result) => println!("{result}"),
        None => eprintln!("invalid expression: {expr:?}"),
    }
}

How it works

  1. Numbers push onto the stack; operators pop two.
  2. ? on pop and parse bails on malformed input.
  3. The final stack value is the result.

Keywords and builtins used here

The run, in numbers

Lines
29
Characters to type
550
Tokens
227
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 130 seconds.

Type this snippet

Step 1 of 1 in Encore, step 15 of 15 in Ownership & borrowing.

← Previous