Skip to content

Instantly share code, notes, and snippets.

@Niedzwiedzw
Created December 1, 2023 06:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Niedzwiedzw/f58847eb723480697a7d89a9a0f249c7 to your computer and use it in GitHub Desktop.
Save Niedzwiedzw/f58847eb723480697a7d89a9a0f249c7 to your computer and use it in GitHub Desktop.
fn next_letter(input: &str) -> Option<(&str, char)> {
input
.chars()
.next()
.and_then(|letter| input.strip_prefix(letter).map(|input| (input, letter)))
}
fn next_value(input: &str) -> Option<(&str, Value)> {
next_digit(input)
.map(|(input, value)| (input, value.pipe(Value::Digit)))
.or_else(|| next_letter(input).map(|(input, value)| (input, value.pipe(Value::Letter))))
}
fn next_digit(input: &str) -> Option<(&str, u32)> {
DIGITS
.iter()
.copied()
.find_map(|(i, digit)| input.strip_prefix(digit).map(|input| (input, i)))
}
#[derive(Debug)]
enum Value {
Letter(char),
Digit(u32),
}
fn parse(mut input: &str) -> Vec<Value> {
std::iter::once(())
.cycle()
.map(|_| {
next_value(input)
.tap_some(|(new_input, _)| input = *new_input)
.map(|(_, value)| value)
})
.take_while(|v| v.is_some())
.flatten()
.collect()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment