-
-
Save rust-play/02c749973cbce934c46292a2e2e334ac 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"; | |
// 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