Skip to content

Instantly share code, notes, and snippets.

@drguildo
Created May 20, 2015 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save drguildo/2f2992e78477a0779ae6 to your computer and use it in GitHub Desktop.
Save drguildo/2f2992e78477a0779ae6 to your computer and use it in GitHub Desktop.
Abstract Syntax Tree
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);
}
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