Evaluate RPN With Match And A Vec Stack
Drive a Vec stack with match: binary operators pop two operands, numbers push, and leftover or missing values become typed errors.
Code
fn evaluate_rpn(tokens: &[&str]) -> Result<i64, String> {
let mut stack: Vec<i64> = Vec::new();
for token in tokens {
match token {
"+" | "-" | "*" | "/" => {
// 二元运算:栈里必须已有两个操作数,顺序先弹 b 再弹 a
let (b, a) = match (stack.pop(), stack.pop()) {
(Some(b), Some(a)) => (b, a),
_ => return Err(format!("not enough operands for {token}")),
};
let value = match token {
"+" => a + b,
"-" => a - b,
"*" => a * b,
_ => a / b,
};
stack.push(value);
}
_ => {
let n: i64 = token.parse().map_err(|_| format!("bad token {token}"))?;
stack.push(n);
}
}
}
match stack.len() {
1 => Ok(stack[0]),
_ => Err(format!("{} values left on the stack", stack.len())),
}
}
fn main() {
println!("{:?}", evaluate_rpn(&["5", "1", "2", "+", "4", "*", "+", "3", "-"]));
println!("{:?}", evaluate_rpn(&["2", "+"]));
println!("{:?}", evaluate_rpn(&["1", "x"]));
}Inside the snippet
Evaluate RPN With Match And A Vec Stack is built around the functions evaluate_rpn and main.
The cycling part of this snippet is for token in tokens. Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match spells out every case; omit one and the code does not compile.
Caveats
- Nothing arrives from a registry; the language ships every API used.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Putting it to use
Signature: fn evaluate_rpn(tokens: &[&str]) -> Result<i64, String>
There are 1 call inside main — evaluate_rpn — executed top to bottom.
How the lines connect
let n: i64 = token.parse().map_err(|_| format!("bad token {token}"))?;
let (b, a) = match (stack.pop(), stack.pop()) {
(Some(b), Some(a)) => (b, a),
_ => return Err(format!("not enough operands for {token}")),
};
let value = match token {
"+" => a + b,
"-" => a - b,
"*" => a * b,
_ => a / b,
};
Interactive Tools for This Topic
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What happens when a call fails?
- Through the type system: failures are `Result` variants the caller must consume.
- How do you run Evaluate RPN With Match And A Vec Stack?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.