1
2use crate::Matrix;
3use std::error::Error;
4use std::ops::Add;
5
6impl<T> Add for Matrix<T>
7
8where T: std::ops::Add + std::clone::Clone + Add<Output = T> {
9
10 type Output = Result<Matrix<T>, Box<dyn Error>>;
11
12 fn add(self, b: Self) -> Result<Matrix<T>, Box<dyn Error>> {
13
14 &self + &b
15
16 }
17
18}
19
20impl<T> Add for &Matrix<T>
21
22where T: std::ops::Add + std::clone::Clone + Add<Output = T> {
23
24 type Output = Result<Matrix<T>, Box<dyn Error>>;
25
26 fn add(self, b: Self) -> Result<Matrix<T>, Box<dyn Error>> {
27
28 let a_dimensions = self.dimensions()?;
29
30 let b_dimensions = b.dimensions()?;
31
32 if a_dimensions == b_dimensions {
33
34 Ok(
35 Matrix(
36 (0..a_dimensions.0)
37 .into_iter()
38 .map(|row| {
39 (0..a_dimensions.1)
40 .into_iter()
41 .map(|column| self.0[row][column].clone() + b.0[row][column].clone())
42 .collect()
43 })
44 .collect()
45 )
46 )
47
48 } else {
49
50 Err("Matrices have different dimensions!")?
51
52 }
53
54 }
55
56}
57
58
59#[cfg(test)]
60mod tests {
61
62 use super::*;
63 #[test]
64 fn test_matrix_addition() {
65
66 let a = Matrix(vec![vec![1,0,3], vec![1,-1,4], vec![2,-1,0]]);
67
68 let b = Matrix(vec![vec![4,2,-1], vec![1,0,6], vec![3,1,4]]);
69
70 let a_plus_b = Matrix(vec![vec![5,2,2], vec![2,-1,10], vec![5,0,4]]);
71
72 assert_eq!((a + b).unwrap(), a_plus_b)
73
74 }
75
76}