Skip to content

Instantly share code, notes, and snippets.

@sumeet
Forked from rust-play/playground.rs
Last active March 31, 2022 21:39
Show Gist options
  • Save sumeet/49108606fb3d058037af9ae25a8b516a to your computer and use it in GitHub Desktop.
Save sumeet/49108606fb3d058037af9ae25a8b516a 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";
#[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] == ')' {
i += 1;
return (Expr::List(exprs), i)
} else if chars[i] == ' ' {
i += 1;
} else {
let (parsed, n) = parse_expression(&s[i..]);
exprs.push(parsed);
i += n;
}
}
panic!("expected ) but never got one")
} 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