Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::ops::{Add, Mul};
- use std::convert::From;
- use std::f64;
- #[derive(Debug)]
- enum Expr {
- Const(f64),
- Sum { lhs: Box<Expr>, rhs: Box<Expr> },
- Prod { lhs: Box<Expr>, rhs: Box<Expr> },
- NaN,
- }
- impl Add for Expr {
- type Output = Self;
- fn add(self, other: Self) -> Self {
- Expr::Sum { lhs: Box::new(self), rhs: Box::new(other) }
- }
- }
- impl Mul for Expr {
- type Output = Self;
- fn mul(self, other: Self) -> Self {
- Expr::Prod { lhs: Box::new(self), rhs: Box::new(other) }
- }
- }
- impl From<Expr> for f64 {
- fn from(expr: Expr) -> f64 {
- use Expr::*;
- match expr {
- Const(n) => n,
- Sum { lhs, rhs } => f64::from(*lhs) + f64::from(*rhs),
- Prod { lhs, rhs } => f64::from(*lhs) * f64::from(*rhs),
- NaN => f64::NAN,
- }
- }
- }
- impl From<f64> for Expr {
- fn from(n: f64) -> Expr {
- if n.is_nan() {
- Expr::NaN
- } else {
- Expr::Const(n)
- }
- }
- }
- fn main() {
- let x: Expr = 16f64.into();
- let y: Expr = 22f64.into();
- let z: Expr = 2.3f64.into();
- let expr = x + y * z;
- println!("{:?}", expr)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement