diff --git a/src/lib.rs b/src/lib.rs index 18fa4e0..d68032f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -26,6 +26,7 @@ use std::fmt; #[cfg(test)] use std::hash; use std::ops::{Add, Div, Mul, Neg, Sub, Rem}; +use std::iter::{Sum, Product}; use std::str::FromStr; use traits::{Zero, One, Num, Inv, Float}; @@ -1069,6 +1070,30 @@ impl Num for Complex { } } +impl Sum for Complex { + fn sum(iter: I) -> Self where I: Iterator { + iter.fold(Self::zero(), |acc, c| acc + c) + } +} + +impl<'a, T: 'a + Num + Clone> Sum<&'a Complex> for Complex { + fn sum(iter: I) -> Self where I: Iterator> { + iter.fold(Self::zero(), |acc, c| acc + c) + } +} + +impl Product for Complex { + fn product(iter: I) -> Self where I: Iterator { + iter.fold(Self::one(), |acc, c| acc * c) + } +} + +impl<'a, T: 'a + Num + Clone> Product<&'a Complex> for Complex { + fn product(iter: I) -> Self where I: Iterator> { + iter.fold(Self::one(), |acc, c| acc * c) + } +} + #[cfg(feature = "serde")] impl serde::Serialize for Complex where T: serde::Serialize @@ -1917,4 +1942,18 @@ mod test { test("1i - 2i"); test("+ 1 - 3.0i"); } + + #[test] + fn test_sum() { + let v = vec![_0_1i, _1_0i]; + assert_eq!(v.iter().sum::(), _1_1i); + assert_eq!(v.into_iter().sum::(), _1_1i); + } + + #[test] + fn test_prod() { + let v = vec![_0_1i, _1_0i]; + assert_eq!(v.iter().product::(), _0_1i); + assert_eq!(v.into_iter().product::(), _0_1i); + } }