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
use std::ops::{Mul, Sub, Add};

use crate::SquareMatrix;

use super::Matrix;
use super::minor::Minor;

pub trait Det: SquareMatrix
{
    type Output;

    /// Returns the determinant of the given matrix
    /// 
    /// |A|
    /// 
    /// # Examples
    /// 
    /// ```rust
    /// let a = [
    ///     [1.0, 0.0],
    ///     [0.0, 1.0]
    /// ];
    /// assert_eq!(a.det(), 1.0);
    /// ```
    fn det(&self) -> Self::Output;
}

impl<F: Clone> Det for [[F; 1]; 1]
where Self: SquareMatrix
{
    type Output = F;

    fn det(&self) -> Self::Output
    {
        self[0][0].clone()
    }
}

impl<F: Clone + Mul<F, Output = F> + Sub<F, Output = F>> Det for [[F; 2]; 2]
where Self: SquareMatrix
{
    type Output = F;

    fn det(&self) -> Self::Output
    {
        self[0][0].clone()*self[1][1].clone() - self[0][1].clone()*self[1][0].clone()
    }
}

macro_rules! det {
    ($i:expr) => {
        impl<F> Det for [[F; $i]; $i]
        where
            F: Clone + Mul<F, Output = F> + Add<F, Output = F>,
            Self: SquareMatrix + Minor<Output = F, Index = (usize, usize)>
        {
            type Output = F;
        
            fn det(&self) -> Self::Output
            {
                (0..self.length())
                    .map(|i| self[i][0].clone()*self.minor((i, 0)))
                    .reduce(|a, b| a + b)
                    .unwrap()
            }
        }
    };
}

det!(3);
det!(4);
det!(5);
det!(6);
det!(7);
det!(8);
det!(9);
det!(10);
det!(11);
det!(12);
det!(13);
det!(14);
det!(15);
det!(16);