1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
use std::{fmt, ops};
use super::{s_val_last, display_header};
use super::{Quadratic, Polynomial};
/// A struct that contains the constants of an equation
/// in the form ax + b.
/// Some useful functions are also implemented.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Linear {
  pub a: f64,
  pub b: f64
}

impl fmt::Display for Linear {
  /// Displays the Linear.
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let part1 = display_header(self.a, String::from("x"));
    let part2 = s_val_last(self.b);
    write!(f, "{part1}{part2}")
  }
}

impl ops::Add<Linear> for Linear {
  type Output = Self;
  fn add(self, other: Self) -> Self::Output {
    Self::new(
      self.a + other.a, 
      self.b + other.b
    )
  }
}

impl ops::Add<f64> for Linear {
  type Output = Self;
  fn add(self, other: f64) -> Self::Output {
    Self::new(self.a, self.b + other)
  }
}
  
impl ops::Sub<Linear> for Linear {
  type Output = Self;
  fn sub(self, other: Self) -> Self::Output {
    Self::new(
      self.a - other.a, 
      self.b - other.b
    )
  }
}

impl ops::Sub<f64> for Linear {
  type Output = Self;
  fn sub(self, other: f64) -> Self::Output {
    Self::new(self.a, self.b - other)
  }
}

impl ops::Mul<Linear> for Linear {
  type Output = Quadratic;
  fn mul(self, other: Linear) -> Self::Output {
    Self::Output::new(
      self.a * other.a,
      self.a * other.b + self.b * other.a,
      self.b * other.b
    )
  }
}
  
impl ops::Mul<f64> for Linear {
  type Output = Self;
  fn mul(self, other: f64) -> Self::Output {
    Self::new(self.a * other, self.b * other)
  }
}

impl Polynomial for Linear {
  /// Evaluates the Linear at the given x.
  fn evaluate(&self, x: f64) -> f64 {
    (self.a * x) +
    self.b
  }
  fn is_zero(&self) -> bool {
    self.a == 0.0 &&
    self.b == 0.0
  }
  fn degree(&self) -> u8 {
    1
  }
}

impl Linear {
  /// Creates a new Linear from the values given.
  pub fn new(a: f64, b: f64) -> Self {
    Self { a, b }
  }

  /// Creates a new Linear from the values given.
  pub fn new_i(a: i32, b: i32) -> Self {
    Self {
      a: a.into(),
      b: b.into()
    }
  }
}