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
mod add;
mod mul;
mod neg;
mod sub;
use std::ops::{Add, Mul, Neg};

#[allow(non_camel_case_types)]
#[derive(Debug, PartialEq, Clone)]
pub struct c<T: Copy + PartialEq>(pub T, pub T);

impl<T: Copy + PartialEq> c<T> {
  /// Extracts the real part of the complex number.
  #[allow(non_snake_case)]
  pub fn Re(&self) -> T {
    self.0
  }

  /// Extracts the imaginary part of the complex number.
  #[allow(non_snake_case)]
  pub fn Im(&self) -> T {
    self.1
  }
}

/// Returns the conjugated complex number.
impl<T: Copy + PartialEq + Neg<Output = T>> c<T> {
  pub fn conj(&self) -> c<T> {
    c(self.0, -self.1)
  }
}

/// Returns the square of the euclidean norm: `|z|^2`
impl<T: Copy + PartialEq + Add<Output = T> + Mul<Output = T>> c<T> {
  pub fn r_square(&self) -> T {
    self.0 * self.0 + self.1 * self.1
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn test_conj() {
    let z = c(1, 2);
    assert_eq!(z.conj(), c(1, -2));
  }

  #[test]
  fn test_r_square() {
    let z = c(1, 2);
    assert_eq!(z.r_square(), (c(1, 2) * c(1, 2).conj()).Re());
  }
}