Morse Code Encode Decode Match Tables

Encode letters to dot-dash tables and decode them back with match arms per symbol, keeping word gaps as slash separators.

RustData Integrity

Code

rustsnippet
30 lines
fn encode_morse(text: &str) -> String {
    text.chars()
        .filter_map(|c| match c {
            'A' => Some(".-"), 'B' => Some("-..."), 'C' => Some("-.-."),
            'D' => Some("-.."), 'E' => Some("."), 'F' => Some("..-."),
            ' ' => Some("/"),
            _ => None,
        })
        .collect::<Vec<&str>>()
        .join(" ")
}

fn decode_morse(code: &str) -> String {
    code.split(' ')
        .filter_map(|sym| match sym {
            ".-" => Some('A'), "-..." => Some('B'), "-.-." => Some('C'),
            "-.." => Some('D'), "." => Some('E'), "..-." => Some('F'),
            "/" => Some(' '),
            _ => None,
        })
        .collect()
}

fn main() {
    let message = "DEAD BEEF";
    let encoded = encode_morse(message);
    println!("{message} -> {encoded}");
    let decoded = decode_morse(&encoded);
    println!("{encoded} -> {decoded}");
}

How this file behaves — Morse Code Encode Decode Match Tables

Under the hood: the functions encode_morse, decode_morse and main.

The match expression is exhaustive — the compiler enforces that no case is missing.

Caveats

  • One-file footprint — imports, where present, are provided by the runtime already.

Applying it

Signature: fn encode_morse(text: &str) -> String

main sequences encode_morse and decode_morse; executing the file runs that flow once.

Statements that matter

.filter_map(|sym| match sym {
    ".-" => Some('A'), "-..." => Some('B'), "-.-." => Some('C'),
    "-.." => Some('D'), "." => Some('E'), "..-." => Some('F'),
    "/" => Some(' '),
    _ => None,
})
.filter_map(|c| match c {
    'A' => Some(".-"), 'B' => Some("-..."), 'C' => Some("-.-."),
    'D' => Some("-.."), 'E' => Some("."), 'F' => Some("..-."),
    ' ' => Some("/"),
    _ => None,
})

Interactive Tools for This Topic

FAQ

How do you run Morse Code Encode Decode Match Tables?
The runtime alone is enough: execute the file as a complete program.