Skip to content

Instantly share code, notes, and snippets.

@syusui-s
Last active May 27, 2017 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syusui-s/0116d62d86537fdaeae5a1eb5cf10df6 to your computer and use it in GitHub Desktop.
Save syusui-s/0116d62d86537fdaeae5a1eb5cf10df6 to your computer and use it in GitHub Desktop.
構文木
enum Literal { Int(i32), }
enum Term<'a> { OpTree(&'a OpTree<'a>), Literal(Literal) }
enum OpType { Add, Sub, Mul, Div }
struct OpTree<'a>(OpType, Term<'a>, Term<'a>);
impl ToString for OpType {
fn to_string(&self) -> String {
use OpType::*;
match self {
&Add => "+",
&Sub => "-",
&Mul => "*",
&Div => "/",
}.into()
}
}
fn print_literal(lit: &Literal) {
use Literal::*;
match lit {
&Int(i) => { print!("{}", i); }
}
}
fn print_term(term: &Term) {
use Term::*;
match term {
&OpTree(ref tree) => print_optree(tree),
&Literal(ref lit) => print_literal(lit),
}
}
fn print_optree<'a>(tree: &'a OpTree) {
let &OpTree(ref op, ref lhs, ref rhs) = tree;
print!("(");
print_term(&lhs);
print!("{}", op.to_string());
print_term(&rhs);
print!(")");
}
fn main() {
let tree1 = OpTree(OpType::Add, Term::Literal(Literal::Int(1)), Term::Literal(Literal::Int(2)));
print_optree(&tree1);
println!();
let tree2 = OpTree(OpType::Sub, Term::OpTree(&tree1), Term::Literal(Literal::Int(2)));
print_optree(&tree2);
println!();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment