Skip to content

Commit 0443a5b

Browse files
committed
Merge #11
11: Implement std::iter::{Sum, Product} r=cuviper a=termoshtt Resolve #3 - Implement `Sum<Complex<T>>` and `Sum<&Complex<T>>` using `Zero` + `AddAssign` - Implement `Product<Complex<T>>` and `Product<&Complex<T>>` using `One` + `MulAssign` `Num` and `NumAssign` are used for type constraint.
2 parents a80c323 + eaf7010 commit 0443a5b

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/lib.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ use std::fmt;
2626
#[cfg(test)]
2727
use std::hash;
2828
use std::ops::{Add, Div, Mul, Neg, Sub, Rem};
29+
use std::iter::{Sum, Product};
2930
use std::str::FromStr;
3031

3132
use traits::{Zero, One, Num, Inv, Float};
@@ -1069,6 +1070,30 @@ impl<T: Num + Clone> Num for Complex<T> {
10691070
}
10701071
}
10711072

1073+
impl<T: Num + Clone> Sum for Complex<T> {
1074+
fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self> {
1075+
iter.fold(Self::zero(), |acc, c| acc + c)
1076+
}
1077+
}
1078+
1079+
impl<'a, T: 'a + Num + Clone> Sum<&'a Complex<T>> for Complex<T> {
1080+
fn sum<I>(iter: I) -> Self where I: Iterator<Item = &'a Complex<T>> {
1081+
iter.fold(Self::zero(), |acc, c| acc + c)
1082+
}
1083+
}
1084+
1085+
impl<T: Num + Clone> Product for Complex<T> {
1086+
fn product<I>(iter: I) -> Self where I: Iterator<Item = Self> {
1087+
iter.fold(Self::one(), |acc, c| acc * c)
1088+
}
1089+
}
1090+
1091+
impl<'a, T: 'a + Num + Clone> Product<&'a Complex<T>> for Complex<T> {
1092+
fn product<I>(iter: I) -> Self where I: Iterator<Item = &'a Complex<T>> {
1093+
iter.fold(Self::one(), |acc, c| acc * c)
1094+
}
1095+
}
1096+
10721097
#[cfg(feature = "serde")]
10731098
impl<T> serde::Serialize for Complex<T>
10741099
where T: serde::Serialize
@@ -1917,4 +1942,18 @@ mod test {
19171942
test("1i - 2i");
19181943
test("+ 1 - 3.0i");
19191944
}
1945+
1946+
#[test]
1947+
fn test_sum() {
1948+
let v = vec![_0_1i, _1_0i];
1949+
assert_eq!(v.iter().sum::<Complex64>(), _1_1i);
1950+
assert_eq!(v.into_iter().sum::<Complex64>(), _1_1i);
1951+
}
1952+
1953+
#[test]
1954+
fn test_prod() {
1955+
let v = vec![_0_1i, _1_0i];
1956+
assert_eq!(v.iter().product::<Complex64>(), _0_1i);
1957+
assert_eq!(v.into_iter().product::<Complex64>(), _0_1i);
1958+
}
19201959
}

0 commit comments

Comments
 (0)