Roman Numerals Round Trip

Convert numbers to roman numerals and back with match-driven mapping, exercising both encoding loops and parse validation.

RustData Integrity

Code

rustsnippet
53 lines
fn to_roman(mut value: u16) -> String {
    // 从大到小逐档扣减:数值到符号的有序映射
    let table = [
        (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
        (100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
        (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"),
    ];
    let mut out = String::new();
    for (amount, symbol) in table {
        while value >= amount {
            out.push_str(symbol);
            value -= amount;
        }
    }
    out
}

fn from_roman(input: &str) -> Result<u16, String> {
    let values = |c: char| match c {
        'I' => Some(1),
        'V' => Some(5),
        'X' => Some(10),
        'L' => Some(50),
        'C' => Some(100),
        'D' => Some(500),
        'M' => Some(1000),
        _ => None,
    };
    let chars: Vec<u16> = input
        .chars()
        .map(|c| values(c).ok_or_else(|| format!("invalid numeral {c:?}")))
        .collect::<Result<_, _>>()?;
    // 减法记法:小值在大值之前时做减
    let mut total = 0;
    for (index, value) in chars.iter().enumerate() {
        if let Some(next) = chars.get(index + 1) {
            if next > value {
                total -= value;
                continue;
            }
        }
        total += value;
    }
    Ok(total)
}

fn main() {
    for year in [2026, 1994, 44, 9] {
        let roman = to_roman(year);
        println!("{year} -> {roman} -> {}", from_roman(&roman).unwrap());
    }
    println!("bad: {:?}", from_roman("XMZ"));
}

How it works

Roman Numerals Round Trip comes down to the functions to_roman, from_roman and main.

A single loop drives the file — for (amount, symbol) in table. Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Signature: fn to_roman(mut value: u16) -> String

Running the file prints labeled results such as bad: — each operation’s effect is visible in the output.

Running the file executes main, which drives to_roman and from_roman in order.

Key statements

.map(|c| values(c).ok_or_else(|| format!("invalid numeral {c:?}")))
.collect::<Result<_, _>>()?;
for (index, value) in chars.iter().enumerate() {
if let Some(next) = chars.get(index + 1) {
if next > value {
total -= value;
continue;
}
}
total += value;
}
let values = |c: char| match c {
'I' => Some(1),
'V' => Some(5),
'X' => Some(10),
'L' => Some(50),
'C' => Some(100),
'D' => Some(500),
'M' => Some(1000),
_ => None,
};

Interactive Tools for This Topic

FAQ

How does the code signal failure?
As `Result` values — each fallible call returns one, and the caller matches or propagates it.
What does Roman Numerals Round Trip print when run?
The script runs standalone; its 1 labeled outputs include `bad:`.