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
use std::ops::{Add,Mul,Sub};
use crate::matrix::MatrixElement;
pub type Vector<A> = Vec<A>;
pub trait VectorTrait<A> {
fn add(&self,other: &Vector<A>) -> Vector<A>;
fn sub(&self,other: &Vector<A>) -> Vector<A>;
fn scale(&self,scale: A) -> Vector<A>;
fn inner(&self,other: &Vector<A>) -> A;
}
pub trait FloatVectorTrait<A> {
fn norm(&self) -> A;
fn normalize(&self) -> Vector<f64>;
}
impl FloatVectorTrait<f64> for Vector<f64> {
fn norm(&self) -> f64 {
self.iter()
.map(|x| x*x)
.fold(0.0,|x,y| x+y)
.sqrt()
}
fn normalize(&self) -> Vector<f64> {
self.scale(1.0/(self.norm()))
}
}
impl<A: MatrixElement + Mul<Output=A> + Add<Output=A> + Sub<Output=A> + Default>
VectorTrait<A> for Vector<A> {
fn add(&self,other: &Vector<A>) -> Vector<A> {
self.iter().zip(other.iter())
.map(|(&x,&y)| x + y)
.collect()
}
fn sub(&self,other: &Vector<A>) -> Vector<A> {
self.iter().zip(other.iter())
.map(|(&x,&y)| x - y)
.collect()
}
fn scale(&self,scale: A) -> Vector<A> {
self.iter()
.map(|&x| x * scale)
.collect()
}
fn inner(&self,other: &Vector<A>) -> A {
self.iter().zip(other.iter())
.map(|(&x,&y)| x*y)
.fold(Default::default(),|x,y| x+y)
}
}