Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. use std::ops::{Add, Mul};
  2. use std::convert::From;
  3. use std::f64;
  4.  
  5. #[derive(Debug)]
  6. enum Expr {
  7. Const(f64),
  8. Sum { lhs: Box<Expr>, rhs: Box<Expr> },
  9. Prod { lhs: Box<Expr>, rhs: Box<Expr> },
  10. NaN,
  11. }
  12.  
  13. impl Add for Expr {
  14. type Output = Self;
  15.  
  16. fn add(self, other: Self) -> Self {
  17. Expr::Sum { lhs: Box::new(self), rhs: Box::new(other) }
  18. }
  19. }
  20.  
  21. impl Mul for Expr {
  22. type Output = Self;
  23.  
  24. fn mul(self, other: Self) -> Self {
  25. Expr::Prod { lhs: Box::new(self), rhs: Box::new(other) }
  26. }
  27. }
  28.  
  29. impl From<Expr> for f64 {
  30. fn from(expr: Expr) -> f64 {
  31. use Expr::*;
  32.  
  33. match expr {
  34. Const(n) => n,
  35. Sum { lhs, rhs } => f64::from(*lhs) + f64::from(*rhs),
  36. Prod { lhs, rhs } => f64::from(*lhs) * f64::from(*rhs),
  37. NaN => f64::NAN,
  38. }
  39. }
  40. }
  41.  
  42. impl From<f64> for Expr {
  43. fn from(n: f64) -> Expr {
  44. if n.is_nan() {
  45. Expr::NaN
  46. } else {
  47. Expr::Const(n)
  48. }
  49. }
  50. }
  51.  
  52. fn main() {
  53. let x: Expr = 16f64.into();
  54. let y: Expr = 22f64.into();
  55. let z: Expr = 2.3f64.into();
  56.  
  57. let expr = x + y * z;
  58.  
  59. println!("{:?}", expr)
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement