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.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Morse Code ConverterEncode text to Morse code or decode Morse back to text, covering letters, digits, and common punctuation.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.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
- How do you run Morse Code Encode Decode Match Tables?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.