rs-03-rpn
1.000
Proposed solution
I'll implement the RPN evaluator according to the specifications.
```rust
// src/lib.rs
pub fn eval_rpn(tokens: &[&str]) -> Result<f64, String> {
let mut stack: Vec<f64> = Vec::new();
for token in tokens {
match *token {
"+" | "-" | "*" | "/" => {
if stack.len() < 2 {
return Err("too few operands".to_string());
}
let b = stack.pop().unwrap();
let a = stack.pop().unwrap();
let result = match *token {
"+" => a + b,
"-" => a - b,
"*" => a * b,
"/" => {
if b == 0.0 {
return Err("division by zero".to_string());
}
a / b
},
_ => unreachable!(), // We already checked for valid operators
};
stack.push(result);
},
_ => {
// Try to parse as a number
match token.parse::<f64>() {
Ok(num) => stack.push(num),
Err(_) => return Err("unknown token".to_string()),
}
}
}
}
if stack.len() != 1 {
return Err("leftover operands".to_string());
}
Ok(stack[0])
}
```Test output (stdout)
running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s running 8 tests ........ test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
System prompt
You are an expert programmer. Solve the task exactly as specified. Output your solution as fenced code blocks using the required file name(s) and the exact function/type signatures requested. Prefer correctness; do not include prose outside code unless asked.