-
-
Save pulcheri/83d088d31dc0b3805be281a8d6797724 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
extern crate regex; | |
#[derive(Debug)] | |
enum GrammarItem { | |
F(String), | |
L(String), | |
R(String), | |
Digits(String), | |
Other(String), | |
} | |
const STR1: &'static str = " | |
FFFR345F2LL | |
"; | |
fn if_number(c: char) -> bool { | |
c >= '0' && c <= '9' | |
} | |
fn get_number<T: Iterator<Item = char>>( | |
c: char, | |
iter: &mut std::iter::Peekable<T>, | |
cond: fn(char) -> bool, | |
) -> String { | |
let mut r = String::new(); | |
r.push(c); | |
while let Some(&c) = iter.peek() { | |
if cond(c) { | |
r.push(c); | |
iter.next(); | |
} else { | |
break; | |
} | |
} | |
r | |
} | |
type Parsed = Vec<GrammarItem>; | |
fn parse(input: &str) -> Result<Parsed, String> { | |
let mut result = Vec::new(); | |
let mut it = input.chars().peekable(); | |
while let Some(c) = it.next() { | |
match c { | |
'0'...'9' => { | |
let n = get_number(c, &mut it, if_number); | |
result.push(GrammarItem::Digits(n)); | |
} | |
'F' => { | |
let r = get_number(c, &mut it, |x| x == 'F'); | |
result.push(GrammarItem::F(r)); | |
} | |
'L' => { | |
let l = get_number(c, &mut it, |x| x == 'L'); | |
result.push(GrammarItem::L(l)); | |
} | |
'R' => { | |
let l = get_number(c, &mut it, |x| x == 'R'); | |
result.push(GrammarItem::R(l)); | |
} | |
_ => { | |
result.push(GrammarItem::Other(c.to_string())); | |
} | |
} | |
} | |
Ok(result) | |
} | |
fn expand(parsed: &Parsed) -> String { | |
//let mut ret = String::new(); | |
let mut v: Vec<String> = Vec::new(); | |
for i in parsed { | |
match i { | |
GrammarItem::F(s) => { | |
let s_ = format!(r#"<span style="color: pink">{}</span>"#, s); | |
v.push(s_); | |
} | |
GrammarItem::L(s) => { | |
let s_ = format!(r#"<span style="color: red">{}</span>"#, s); | |
v.push(s_); | |
} | |
GrammarItem::R(s) => { | |
let s_ = format!(r#"<span style="color: green">{}</span>"#, s); | |
v.push(s_); | |
} | |
GrammarItem::Digits(s) => { | |
let s_ = format!(r#"<span style="color: orange">{}</span>"#, s); | |
v.push(s_); | |
} | |
GrammarItem::Other(s) => { | |
v.push(s.clone()); | |
} | |
_ => {} | |
} | |
} | |
v.join("") | |
} | |
fn main() { | |
let x = 1; | |
println!("{:?}", x); | |
if let Ok(r) = parse(&STR1) { | |
//println!("{:?}", r); | |
let x = expand(&r); | |
println!("{:?}", x); | |
} | |
//let x = rolldice_sum_prob(8, 3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment