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
use crate::arrays::Array;
use crate::prelude::ArrayError;
use crate::traits::{
    manipulate::iter::ArrayIter,
    math::ArrayMath,
    types::numeric::Numeric,
};

impl <N: Numeric> ArrayMath<N> for Array<N> {

    fn power(&self, value: N) -> Result<Array<N>, ArrayError> {
        self.map(|i| N::from(i.to_f64().powf(value.to_f64())))
    }

    fn product(&self) -> Result<N, ArrayError> {
        Ok(self.elements.iter().fold(N::ONE, |acc, x| N::from(acc.to_f64() * x.to_f64())))
    }

    fn sum(&self) -> Result<N, ArrayError> {
        Ok(self.elements.iter().fold(N::ZERO, |acc, x| N::from(acc.to_f64() + x.to_f64())))
    }

    fn cumsum(&self) -> Result<Array<N>, ArrayError> {
        let mut acc = N::ZERO;
        self.map(|&x| {
            acc = N::from(acc.to_f64() + x.to_f64());
            acc
        })
    }
}

impl <N: Numeric> ArrayMath<N> for Result<Array<N>, ArrayError> {

    fn power(&self, value: N) -> Result<Array<N>, ArrayError> {
        self.clone()?.power(value)
    }

    fn product(&self) -> Result<N, ArrayError> {
        self.clone()?.product()
    }

    fn sum(&self) -> Result<N, ArrayError> {
        self.clone()?.sum()
    }

    fn cumsum(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.cumsum()
    }
}