From 97fcd46f4dadb18e22c7a74309c93a3897a9b08c Mon Sep 17 00:00:00 2001 From: Axect Date: Sun, 17 Jan 2021 05:25:02 +0900 Subject: [PATCH] IMPL: FPVector & Vector for Vec> (#35) --- src/structure/complex.rs | 84 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 83 insertions(+), 1 deletion(-) diff --git a/src/structure/complex.rs b/src/structure/complex.rs index dd20137c..61fd77ad 100644 --- a/src/structure/complex.rs +++ b/src/structure/complex.rs @@ -1,5 +1,7 @@ use num_complex::Complex; +use crate::traits::fp::FPVector; use crate::traits::math::{Vector, Normed, Norm, InnerProduct}; +use crate::traits::sugar::VecOps; impl Vector for Complex { type Scalar = Self; @@ -23,7 +25,7 @@ impl Normed for Complex { match kind { Norm::L1 => self.l1_norm(), Norm::L2 => Complex::::norm(*self), - _ => panic!("No more norms form complex"), + _ => unimplemented!(), } } @@ -40,3 +42,83 @@ impl InnerProduct for Complex { self.conj() * rhs } } + +impl FPVector for Vec> { + type Scalar = Complex; + + fn fmap(&self, f: F) -> Self + where + F: Fn(Self::Scalar) -> Self::Scalar { + self.iter().map(|&x| f(x)).collect() + } + + fn zip_with(&self, f: F, other: &Self) -> Self + where + F: Fn(Self::Scalar, Self::Scalar) -> Self::Scalar { + self.iter().zip(other.iter()).map(|(&x, &y)| f(x,y)).collect() + } + + fn reduce(&self, init: T, f: F) -> Self::Scalar + where + F: Fn(Self::Scalar, Self::Scalar) -> Self::Scalar, + T: Into { + self.iter().fold(init.into(), |x, &y| f(x,y)) + } + + fn filter(&self, f: F) -> Self + where + F: Fn(Self::Scalar) -> bool { + self.into_iter().filter(|&x| f(*x)).map(|&t| t).collect() + } + + fn take(&self, n: usize) -> Self { + self.iter().take(n).map(|&x| x).collect() + } + + fn skip(&self, n: usize) -> Self { + self.iter().skip(n).map(|&x| x).collect() + } + + fn sum(&self) -> Self::Scalar { + self.iter().sum() + } + + fn prod(&self) -> Self::Scalar { + self.iter().product() + } +} + +impl Vector for Vec> { + type Scalar = Complex; + + fn add_vec<'a, 'b>(&'a self, rhs: &'b Self) -> Self { + self.zip_with(|x, y| x + y, rhs) + } + + fn sub_vec<'a, 'b>(&'a self, rhs: &'b Self) -> Self { + self.zip_with(|x, y| x - y, rhs) + } + + fn mul_scalar(&self, rhs: Self::Scalar) -> Self { + self.fmap(|x| x * rhs) + } +} + +impl Normed for Vec> { + type UnsignedScalar = f64; + + fn norm(&self, kind: Norm) -> Self::UnsignedScalar { + match kind { + Norm::L1 => self.iter().map(|x| Complex::::norm(*x).abs()).sum(), + _ => unimplemented!() + } + } + + fn normalize(&self, kind: Norm) -> Self + where + Self: Sized { + unimplemented!() + } +} + +impl VecOps for Vec> {}