From b469f7458b9e44b50a0a6477d07ce674c23f104f Mon Sep 17 00:00:00 2001 From: SinTan1729 Date: Sat, 27 May 2023 00:44:36 -0500 Subject: [PATCH] new: Added conversion trait --- src/lib.rs | 39 +++++++++++++++++++++++++++++++++++++++ src/tests.rs | 10 ++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 8c43d3c..a827db4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -439,3 +439,42 @@ impl + Mul + Copy + Zero + Neg> Sub for Mat } } } + +/// Trait for conversion between matrices of different types. +/// It only has a `convert_to()` method. +/// This is needed since negative trait bound are not supported in stable Rust +/// yet, so we'll have a conflict trying to implement [`From`]. +/// I plan to change this to the default From trait as soon as some sort +/// of specialization system is implemented. +/// You can track this issue [here](https://github.com/rust-lang/rust/issues/42721). +pub trait MatrixInto { + /// Method for converting a matrix into a matrix of type `Matrix` + fn matrix_into(self) -> Matrix; +} + +/// Blanket implementation of MatrixInto for converting `Matrix` to `Matrix` whenever +/// `S` implements `Into`. +/// # Example +/// ``` +/// use matrix_basic::Matrix; +/// use matrix_basic::MatrixInto; +/// +/// let a = Matrix::from(vec![vec![1, 2, 3], vec![0, 1, 2]]).unwrap(); +/// let b = Matrix::from(vec![vec![1.0, 2.0, 3.0], vec![0.0, 1.0, 2.0]]).unwrap(); +/// let c: Matrix = a.matrix_into(); +/// +/// assert_eq!(c, b); +/// ``` +impl> MatrixInto for Matrix { + fn matrix_into(self) -> Matrix { + let mut out = Vec::new(); + for row in self.entries { + let mut new_row: Vec = Vec::new(); + for entry in row { + new_row.push(entry.into()); + } + out.push(new_row) + } + Matrix { entries: out } + } +} diff --git a/src/tests.rs b/src/tests.rs index 14eb605..9afaf39 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -1,5 +1,6 @@ #[cfg(test)] use crate::Matrix; + #[test] fn mul_test() { let a = Matrix::from(vec![vec![1, 2, 4], vec![3, 4, 9]]).unwrap(); @@ -58,3 +59,12 @@ fn echelon_test() { assert_eq!(m.column_echelon(), b); assert_eq!(m.reduced_row_echelon(), c); } + +#[test] +fn conversion_test() { + let a = Matrix::from(vec![vec![1, 2, 3], vec![0, 1, 2]]).unwrap(); + let b = Matrix::from(vec![vec![1.0, 2.0, 3.0], vec![0.0, 1.0, 2.0]]).unwrap(); + + use crate::MatrixInto; + assert_eq!(a.matrix_into(), b); +}