-
-
Save tmiller/5aeaea447ce10c8d7c9d3eb2a1cda6fa to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains hidden or 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
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