rust_linear_algebra/vector/ops/
mul.rs

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

impl<K, T> Mul<T> for Vector<K>
where
    K: Mul<T, Output = K> + Copy,
    T: Copy,
{
    type Output = Vector<K>;

    fn mul(self, rhs: T) -> Self::Output {
        let elements = self.iter().map(|&a| a * rhs).collect();
        Vector { elements }
    }
}

impl<K> Vector<K>
where
    K: Mul<Output = K> + Copy + Default,
{
    pub fn scl(&mut self, a: K) {
        self.elements = self.iter().map(|&n| n * a).collect();
    }
}

impl<K> Mul for Vector<K>
where
    K: Mul<Output = K> + Copy + Default,
    K: Add<Output = K> + Copy,
{
    type Output = K;

    fn mul(self, rhs: Self) -> Self::Output {
        if self.len() != rhs.len() {
            panic!("The vector need to be on the same plan");
        }

        self.iter()
            .zip(rhs.iter())
            .map(|(&a, &b)| a * b)
            .fold(K::default(), |acc, x| acc + x)
    }
}

impl<K> Vector<K>
where
    K: Add<Output = K> + Copy + Default,
    K: Mul<Output = K> + Copy + Default,
{
    pub fn dot(&self, v: Self) -> K {
        if self.len() != v.len() {
            panic!("The vector need to be on the same plan");
        }

        self.iter()
            .zip(v.iter())
            .map(|(&a, &b)| a * b)
            .fold(K::default(), |acc, x| acc + x)
    }
}