Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. // Mathematical "errors" we want to catch
  2. #[derive(Debug)]
  3. pub enum MathError {
  4. DivisionByZero,
  5. NonPositiveLogarithm,
  6. NegativeSquareRoot,
  7. }
  8.  
  9. pub type MathResult = Result<f64, MathError>;
  10.  
  11. pub fn div(x: f64, y: f64) -> MathResult {
  12. if y == 0.0 {
  13. // This operation would `fail`, instead let's return the reason of
  14. // the failure wrapped in `Err`
  15. Err(MathError::DivisionByZero)
  16. } else {
  17. // This operation is valid, return the result wrapped in `Ok`
  18. Ok(x / y)
  19. }
  20. }
  21.  
  22. pub fn sqrt(x: f64) -> MathResult {
  23. if x < 0.0 {
  24. Err(MathError::NegativeSquareRoot)
  25. } else {
  26. Ok(x.sqrt())
  27. }
  28. }
  29.  
  30. pub fn ln(x: f64) -> MathResult {
  31. if x <= 0.0 {
  32. Err(MathError::NonPositiveLogarithm)
  33. } else {
  34. Ok(x.ln())
  35. }
  36. }
  37.  
  38. // `op(x, y)` === `sqrt(ln(x / y))`
  39. fn check_all(x: f64, y: f64) -> f64 {
  40. // This is a three level match pyramid!
  41. match div(x, y) {
  42. Err(why) => panic!("{:?}", why),
  43. Ok(ratio) => match ln(ratio) {
  44. Err(why) => panic!("{:?}", why),
  45. Ok(ln) => match sqrt(ln) {
  46. Err(why) => panic!("{:?}", why),
  47. Ok(sqrt) => sqrt,
  48. },
  49. },
  50. }
  51. }
  52. fn main() {
  53. // Will this fail?
  54. println!("{}", check_all(1.0, 10.0));
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement