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

use crate::base::base_type::Numeric;
use crate::prelude::{Array, ArrayBase};

// ==== Add

impl <N: Numeric> Add<Array<N>> for Array<N> {
    type Output = Array<N>;

    fn add(self, other: Self) -> Self::Output {
        assert_eq!(self.get_shape(), other.get_shape(), "Arrays must have the same shape");

        let elements = self.elements.into_iter()
            .zip(other.elements.into_iter())
            .map(|(a, b)| a + b)
            .collect();

        Array::new(elements, self.shape)
    }
}

impl <N: Numeric> Add<N> for Array<N> {
    type Output = Array<N>;

    fn add(self, other: N) -> Self::Output {
        self.map(|i| *i + other)
            .reshape(self.shape)
    }
}

// ==== Sub

impl <N: Numeric> Sub<Array<N>> for Array<N> {
    type Output = Array<N>;

    fn sub(self, other: Self) -> Self::Output {
        assert_eq!(self.get_shape(), other.get_shape(), "Arrays must have the same shape");

        let elements = self.elements.into_iter()
            .zip(other.elements.into_iter())
            .map(|(a, b)| a - b)
            .collect();

        Array::new(elements, self.shape)
    }
}

impl <N: Numeric> Sub<N> for Array<N> {
    type Output = Array<N>;

    fn sub(self, other: N) -> Self::Output {
        self.map(|i| *i - other)
            .reshape(self.shape)
    }
}

// ==== Mul

impl <N: Numeric> Mul<Array<N>> for Array<N> {
    type Output = Array<N>;

    fn mul(self, other: Self) -> Self::Output {
        assert_eq!(self.get_shape(), other.get_shape(), "Arrays must have the same shape");

        let elements = self.elements.into_iter()
            .zip(other.elements.into_iter())
            .map(|(a, b)| a * b)
            .collect();

        Array::new(elements, self.shape)
    }
}

impl <N: Numeric> Mul<N> for Array<N> {
    type Output = Array<N>;

    fn mul(self, other: N) -> Self::Output {
        self.map(|i| *i * other)
            .reshape(self.shape)
    }
}

// ==== Div

impl <N: Numeric> Div<Array<N>> for Array<N> {
    type Output = Array<N>;

    fn div(self, other: Self) -> Self::Output {
        assert_eq!(self.get_shape(), other.get_shape(), "Arrays must have the same shape");

        let elements = self.elements.into_iter()
            .zip(other.elements.into_iter())
            .map(|(a, b)| a / b)
            .collect();

        Array::new(elements, self.shape)
    }
}

impl <N: Numeric> Div<N> for Array<N> {
    type Output = Array<N>;

    fn div(self, other: N) -> Self::Output {
        self.map(|i| *i / other)
            .reshape(self.shape)
    }
}