Created
September 20, 2019 21:25
-
-
Save rust-play/847de1a9de64489509628414fa25f97e to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
#![allow(dead_code, unconditional_recursion)] | |
trait StringRep { | |
fn rep(&self) -> String; | |
} | |
#[derive(Debug)] | |
enum Token { | |
Add((Box<Token>, Box<Token>)), | |
Sub((Box<Token>, Box<Token>)), | |
Constant(i32), | |
} | |
fn const_fold(token: Box<Token>) -> Token { | |
match *token { | |
Token::Add((l, r)) => match (const_fold(l), const_fold(r)) { | |
(Token::Constant(l_1), Token::Constant(r_1)) => Token::Constant(l_1 + r_1), | |
_ => unimplemented!(), | |
}, | |
Token::Sub((l, r)) => match (const_fold(l), const_fold(r)) { | |
(Token::Constant(l_1), Token::Constant(r_1)) => Token::Constant(l_1 - r_1), | |
_ => unimplemented!(), | |
}, | |
_ => unimplemented!(), | |
} | |
} | |
impl Token { | |
fn eval(&self) -> i32 { | |
match self { | |
Token::Add((l, r)) => l.eval() + r.eval(), | |
Token::Sub((l, r)) => l.eval() + r.eval(), | |
Token::Constant(constant_val) => *constant_val, | |
} | |
} | |
} | |
impl StringRep for Token { | |
fn rep(&self) -> String { | |
match self { | |
Token::Add((l, r)) => format!("({} + {})", l.rep(), r.rep()), | |
Token::Sub((l, r)) => format!("({} - {})", l.rep(), r.rep()), | |
Token::Constant(constant_val) => constant_val.to_string(), | |
} | |
} | |
} | |
fn main() { | |
let ast = Token::Add(( | |
Box::new(Token::Constant(6)), | |
Box::new(Token::Sub(( | |
Box::new(Token::Constant(7)), | |
Box::new(Token::Constant(3)), | |
))), | |
)); | |
println!( | |
"AST: {:?}\nRESULT: {}\nSTRING REPRESENTATION: {}", | |
ast, | |
ast.eval(), | |
ast.rep() | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment