rust_linear_algebra/vector/ops/
mul.rs1use super::super::Vector;
2use std::ops::{Add, Mul};
3
4impl<K, T> Mul<T> for Vector<K>
5where
6 K: Mul<T, Output = K> + Copy,
7 T: Copy,
8{
9 type Output = Vector<K>;
10
11 fn mul(self, rhs: T) -> Self::Output {
12 let elements = self.iter().map(|&a| a * rhs).collect();
13 Vector { elements }
14 }
15}
16
17impl<K> Vector<K>
18where
19 K: Mul<Output = K> + Copy + Default,
20{
21 pub fn scl(&mut self, a: K) {
22 self.elements = self.iter().map(|&n| n * a).collect();
23 }
24}
25
26impl<K> Mul for Vector<K>
27where
28 K: Mul<Output = K> + Copy + Default,
29 K: Add<Output = K> + Copy,
30{
31 type Output = K;
32
33 fn mul(self, rhs: Self) -> Self::Output {
34 if self.len() != rhs.len() {
35 panic!("The vector need to be on the same plan");
36 }
37
38 self.iter()
39 .zip(rhs.iter())
40 .map(|(&a, &b)| a * b)
41 .fold(K::default(), |acc, x| acc + x)
42 }
43}
44
45impl<K> Vector<K>
46where
47 K: Add<Output = K> + Copy + Default,
48 K: Mul<Output = K> + Copy + Default,
49{
50 pub fn dot(&self, v: Self) -> K {
51 if self.len() != v.len() {
52 panic!("The vector need to be on the same plan");
53 }
54
55 self.iter()
56 .zip(v.iter())
57 .map(|(&a, &b)| a * b)
58 .fold(K::default(), |acc, x| acc + x)
59 }
60}