Skip to content

Instantly share code, notes, and snippets.

Created November 25, 2017 02:59
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 anonymous/e8d664305be2916927d8c894029ca771 to your computer and use it in GitHub Desktop.
Save anonymous/e8d664305be2916927d8c894029ca771 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
enum Expr {
Val(i32),
Div(Box<Expr>, Box<Expr>),
}
fn eval(expr: Expr) -> Option<i32> {
match expr {
Expr::Val(x) => Some(x),
Expr::Div(x, y) => {
let x = eval(*x)?;
let y = eval(*y)?;
safediv(x, y)
}
}
}
fn safediv(x: i32, y: i32) -> Option<i32> {
if y == 0 {
None
} else {
Some(x / y)
}
}
fn main() {
println!("{:?}", eval(Expr::Val(10)));
println!(
"{:?}",
eval(Expr::Div(Box::new(Expr::Val(10)), Box::new(Expr::Val(5))))
);
println!(
"{:?}",
eval(Expr::Div(Box::new(Expr::Val(10)), Box::new(Expr::Val(0))))
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment