-
-
Save sumeet/49108606fb3d058037af9ae25a8b516a to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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