Expand Compact Range Notation

Expand compact range notation like 1-3,5,8-9 by splitting on commas, matching each part with split_once, and flat_mapping ranges into one vector.

RustCli Tooling

Code

rustsnippet
18 lines
fn expand(spec: &str) -> Vec<u32> {
    // expand compact range notation: "1-3,5,8-9" becomes a full sequence
    spec.split(',')
        .flat_map(|part| match part.split_once('-') {
            Some((lo, hi)) => {
                let (lo, hi) = (lo.parse::<u32>().unwrap(), hi.parse::<u32>().unwrap());
                (lo..=hi).collect::<Vec<_>>()
            }
            None => vec![part.parse::<u32>().unwrap()],
        })
        .collect()
}

fn main() {
    for spec in ["1-3,5,8-9", "4", "2-4,7-7"] {
        println!("{spec} -> {:?}", expand(spec));
    }
}

Expand Compact Range Notation: inside the code

The snippet is organized around the functions expand and main.

Repetition is confined to for spec in ["1-3,5,8-9", "4", "2-4,7-7"] — the rest of the file is straight-line. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

What to watch for

  • No dependencies section needed; the standard library is the whole story.

Putting it to use

The signature that runs: fn expand(spec: &str) -> Vec<u32>

The demo flow inside main is expand — run the file to see it end to end.

Core lines

Some((lo, hi)) => {
    let (lo, hi) = (lo.parse::<u32>().unwrap(), hi.parse::<u32>().unwrap());
    (lo..=hi).collect::<Vec<_>>()
}

Interactive Tools for This Topic

FAQ

How do you run Expand Compact Range Notation?
The runtime alone is enough: execute the file as a complete program.