rust_tensors/
addressable.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
61
pub trait Addressable: PartialEq + Ord + Sized + Copy {
    fn get_dimension_count() -> u32;
    fn new_from_value_vec(values: Vec<i64>) -> Self;
    fn get_item_at_dimension_index(&self, dimension_index: u32) -> &i64;
    fn add(&self, other: &Self) -> Self {
        Self::new_from_value_vec(
            (0..Self::get_dimension_count())
                .into_iter()
                .map(|dimension_index: u32| {
                    self.get_item_at_dimension_index(dimension_index)
                        + other.get_item_at_dimension_index(dimension_index)
                })
                .collect(),
        )
    }
    fn subtract(&self, other: &Self) -> Self {
        Self::new_from_value_vec(
            (0..Self::get_dimension_count())
                .into_iter()
                .map(|dimension_index: u32| {
                    self.get_item_at_dimension_index(dimension_index)
                        - other.get_item_at_dimension_index(dimension_index)
                })
                .collect(),
        )
    }
    fn difference(&self, other: &Self) -> Self {
        Self::new_from_value_vec(
            (0..Self::get_dimension_count())
                .into_iter()
                .map(|dimension_index: u32| {
                    (self.get_item_at_dimension_index(dimension_index)
                        - other.get_item_at_dimension_index(dimension_index))
                    .abs()
                })
                .collect(),
        )
    }
    fn distance(&self, other: &Self) -> f64 {
        ((0..Self::get_dimension_count())
            .into_iter()
            .map(|dimension_index: u32| {
                (self.get_item_at_dimension_index(dimension_index)
                    - other.get_item_at_dimension_index(dimension_index))
                .pow(2)
            })
            .reduce(|acc, e| acc + e)
            .unwrap() as f64)
            .sqrt()
    }
    fn scale(&self, scalar: f64) -> Self {
        Self::new_from_value_vec(
            (0..Self::get_dimension_count())
                .into_iter()
                .map(|dimension_index: u32| {
                    ((*self.get_item_at_dimension_index(dimension_index) as f64) * scalar) as i64
                })
                .collect(),
        )
    }
}