Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created March 31, 2022 17:38
Show Gist options
  • Save rust-play/02c749973cbce934c46292a2e2e334ac to your computer and use it in GitHub Desktop.
Save rust-play/02c749973cbce934c46292a2e2e334ac to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
const SAMPLE_FLAT_LIST: &str = "(a b c d e f)";
const SAMPLE_NESTED_LIST: &str = "(a b c (d (e word-word) f))";
const SAMPLE_WORD: &str = "sample-word";
// sum type (has only one)
#[derive(Debug)]
enum Expr {
List(Vec<Expr>),
Word(String),
}
fn parse_expression(s: &str) -> (Expr, usize) {
let chars: Vec<char> = s.chars().collect();
dbg!(&chars[0]);
if chars[0] == '(' {
let mut i = 1;
let mut exprs = vec![];
while i < chars.len() {
if chars[i] == ')' || chars[i] == ' ' {
i += 1;
break;
}
let (parsed, n) = parse_expression(&s[i..]);
exprs.push(parsed);
i += n;
}
(Expr::List(exprs), i)
} else {
let mut accumed_word = String::new();
let mut i = 0;
while i < chars.len() {
if chars[i] == ' ' {
i += 1;
break;
} else if chars[i] == ')' {
break;
} else {
accumed_word.push(chars[i]);
i += 1;
}
}
(Expr::Word(accumed_word), i)
}
}
fn main() {
let expr = parse_expression(SAMPLE_WORD);
println!("{:?}", expr); // Word
let expr = parse_expression(SAMPLE_FLAT_LIST);
println!("{:#?}", expr); // List
let expr = parse_expression(SAMPLE_NESTED_LIST);
println!("{:#?}", expr); // List
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment