Created
May 20, 2015 12:51
-
-
Save drguildo/2f2992e78477a0779ae6 to your computer and use it in GitHub Desktop.
Abstract Syntax Tree
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
mod simple; | |
use simple::Expr::{Number, Add, Multiply}; | |
fn main() { | |
println!("Let's compute!"); | |
let e = Add(Box::new(Add(Box::new(Number(1)), | |
Box::new(Number(1)))), | |
Box::new(Multiply(Box::new(Number(2)), | |
Box::new(Number(4))))); | |
println!("{}", e); | |
} |
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
use std::fmt; | |
pub enum Expr { | |
Number(i32), | |
Add(Box<Expr>, Box<Expr>), | |
Multiply(Box<Expr>, Box<Expr>), | |
} | |
impl fmt::Display for Expr { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
let s = match *self { | |
Expr::Number(n) => n.to_string(), | |
Expr::Add(ref l, ref r) => format!("({} + {})", l.to_string(), r.to_string()), | |
Expr::Multiply(ref l, ref r) => format!("({} * {})", l.to_string(), r.to_string()), | |
}; | |
write!(f, "{}", s) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment