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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
use num::{Num, Zero, One};
use rustc_serialize::{Encodable, Decodable};
use std::fmt::Debug;
pub trait Vector: Clone {
type Scalar: Num + Zero + One + Copy + Encodable + Decodable + Default + Debug;
fn dimension(&self) -> usize;
fn at(&self, i: usize) -> Self::Scalar;
fn mut_at(&mut self, i: usize) -> &mut Self::Scalar;
fn dot(&self, other: &Self) -> Self::Scalar {
let mut result = Self::Scalar::zero();
for i in 0..self.dimension() {
result = result + self.at(i) * other.at(i)
}
result
}
}
impl Vector for f64 {
type Scalar = f64;
fn dimension(&self) -> usize {
1
}
fn at(&self, _: usize) -> f64 {
*self
}
fn mut_at(&mut self, _: usize) -> &mut f64 {
self
}
fn dot(&self, other: &f64) -> f64 {
self * other
}
}
macro_rules! vec_impl_for_array {
($v:expr) => {
impl Vector for [f64; $v] {
type Scalar = f64;
fn dimension(&self) -> usize{ $v }
fn at(&self, index: usize) -> f64 {
self[index]
}
fn mut_at(&mut self, index: usize) -> &mut f64 {
&mut self[index]
}
}
}
}
vec_impl_for_array! { 1 }
vec_impl_for_array! { 2 }
vec_impl_for_array! { 3 }
vec_impl_for_array! { 4 }
vec_impl_for_array! { 5 }
vec_impl_for_array! { 6 }
vec_impl_for_array! { 7 }
vec_impl_for_array! { 8 }
vec_impl_for_array! { 9 }
vec_impl_for_array! { 10 }
vec_impl_for_array! { 11 }
vec_impl_for_array! { 12 }
vec_impl_for_array! { 13 }
vec_impl_for_array! { 14 }
vec_impl_for_array! { 15 }
vec_impl_for_array! { 16 }
vec_impl_for_array! { 17 }
vec_impl_for_array! { 18 }
vec_impl_for_array! { 19 }
vec_impl_for_array! { 20 }
vec_impl_for_array! { 21 }
vec_impl_for_array! { 22 }
vec_impl_for_array! { 23 }
vec_impl_for_array! { 24 }
vec_impl_for_array! { 25 }
vec_impl_for_array! { 26 }
vec_impl_for_array! { 27 }
vec_impl_for_array! { 28 }
vec_impl_for_array! { 29 }
vec_impl_for_array! { 30 }
vec_impl_for_array! { 31 }
vec_impl_for_array! { 32 }
#[cfg(test)]
mod tests {
#[test]
fn dot() {
use linear_algebra::Vector;
let a = [1.0, 2.0];
let b = [3.0, 4.0];
assert_eq!(11.0, a.dot(&b))
}
}