Selaa lähdekoodia

:sparkles: added complex! macro

Felix Bytow 2 vuotta sitten
vanhempi
sitoutus
19342e19cf
2 muutettua tiedostoa jossa 40 lisäystä ja 4 poistoa
  1. 2 1
      CHANGELOG.md
  2. 38 3
      src/types/complex.rs

+ 2 - 1
CHANGELOG.md

@@ -3,7 +3,8 @@
 ## Release 0.3.0
 
 - `Numeric::whole` is now `unsafe`.
-- Renamed the mathematical functions (`fabs` to `abs`, `fsqrt` to `sqrt`, etc.)
+- Renamed the mathematical functions (`fabs` to `abs`, `fsqrt` to `sqrt`, etc.).
+- added `complex!` macro for more comfortable `Complex` creation.
 
 ## Release 0.2.3
 

+ 38 - 3
src/types/complex.rs

@@ -7,14 +7,14 @@ use crate::{Float, Numeric, Primitive};
 /// # Example
 ///
 /// ```rust
-/// # use lineal::{Complex, Float, Numeric};
+/// # use lineal::{Complex, complex, Float, Numeric};
 /// let c = Complex { real: 9.0, imag: 0.0 };
 /// assert_eq!(format!("{:?}", c), "Complex { real: 9.0, imag: 0.0 }");
 ///
 /// let three = c.sqrt().real;
 /// assert_eq!(three, 3.0);
 ///
-/// let i: Complex<f32> = Complex::real(-1.0).sqrt();
+/// let i: Complex<f32> = complex!(-1.0).sqrt();
 /// assert_eq!(i, Complex::i());
 ///
 /// let a = Complex { real: 2.0, imag: 0.5 };
@@ -23,7 +23,7 @@ use crate::{Float, Numeric, Primitive};
 /// assert_eq!(a_squared.sqrt(), a);
 ///
 /// let x = (16.0).sqrt();
-/// let y = Complex::real(16.0).sqrt().real;
+/// let y = complex!(16.0).sqrt().real;
 /// assert_eq!(x, y);
 /// ```
 #[derive(Debug, Copy, Clone)]
@@ -32,6 +32,28 @@ pub struct Complex<T: Float + Numeric + Primitive> {
     pub imag: T,
 }
 
+#[macro_export]
+macro_rules! complex {
+    ($real:expr, $imag:expr) => {
+        Complex { real: $real, imag: $imag }
+    };
+    ($real:expr) => {
+        Complex { real: $real, imag: 0.0 }
+    };
+    ($($field:ident = $value:expr),* $(,)?) => {
+        Complex {
+            $( $field: $value, )*
+            ..Complex::default()
+        }
+    }
+}
+
+impl<T: Float + Numeric + Primitive> Default for Complex<T> {
+    fn default() -> Self {
+        unsafe { Complex::whole(0) }
+    }
+}
+
 impl<T: Float + Numeric + Primitive> Complex<T> {
     pub fn real(value: T) -> Self {
         Self {
@@ -213,6 +235,19 @@ impl<T: Float + Numeric + Primitive> Numeric for Complex<T> {
 mod tests {
     use crate::{Complex, Float};
 
+    #[test]
+    fn macro_creation() {
+        let a = complex!(-1.0);
+        let b = complex!(real = -1.0,);
+        assert_eq!(a, b);
+        let c = complex!(imag = 1.0,);
+        assert_eq!(a.sqrt(), c);
+        let d = complex!(real = -1.0, imag = 0.0,);
+        assert_eq!(c * c, d);
+        let e = complex!(-1.0, 0.0);
+        assert_eq!(a, e);
+    }
+
     #[test]
     fn division() {
         let mut a: Complex<f32> = Complex { real: 3.0, imag: 2.0 };