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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Scientific Notation ConverterConvert numbers between plain decimal and scientific notation, optionally fixing the significant digits and splitting out the mantissa and exponent.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
FAQ
- How do you run Expand Compact Range Notation?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.