Skip to content

Commit eaf7010

Browse files
committed
Use folds for Sum and Product
Folding can be faster for some iterators, and this way we also don't need to require `NumAssign`.
1 parent 84b6ae8 commit eaf7010

File tree

1 file changed

+9
-25
lines changed

1 file changed

+9
-25
lines changed

src/lib.rs

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ use std::ops::{Add, Div, Mul, Neg, Sub, Rem};
2929
use std::iter::{Sum, Product};
3030
use std::str::FromStr;
3131

32-
use traits::{Zero, One, Num, NumAssign, Inv, Float};
32+
use traits::{Zero, One, Num, Inv, Float};
3333

3434
// FIXME #1284: handle complex NaN & infinity etc. This
3535
// probably doesn't map to C's _Complex correctly.
@@ -1070,43 +1070,27 @@ impl<T: Num + Clone> Num for Complex<T> {
10701070
}
10711071
}
10721072

1073-
impl<T: Clone + NumAssign> Sum for Complex<T> {
1073+
impl<T: Num + Clone> Sum for Complex<T> {
10741074
fn sum<I>(iter: I) -> Self where I: Iterator<Item = Self> {
1075-
let mut s = Self::zero();
1076-
for c in iter {
1077-
s += c;
1078-
}
1079-
s
1075+
iter.fold(Self::zero(), |acc, c| acc + c)
10801076
}
10811077
}
10821078

1083-
impl<'a, T: 'a + Clone + NumAssign> Sum<&'a Complex<T>> for Complex<T> {
1079+
impl<'a, T: 'a + Num + Clone> Sum<&'a Complex<T>> for Complex<T> {
10841080
fn sum<I>(iter: I) -> Self where I: Iterator<Item = &'a Complex<T>> {
1085-
let mut s = Self::zero();
1086-
for c in iter {
1087-
s += c;
1088-
}
1089-
s
1081+
iter.fold(Self::zero(), |acc, c| acc + c)
10901082
}
10911083
}
10921084

1093-
impl<T: Clone + NumAssign> Product for Complex<T> {
1085+
impl<T: Num + Clone> Product for Complex<T> {
10941086
fn product<I>(iter: I) -> Self where I: Iterator<Item = Self> {
1095-
let mut s = Self::one();
1096-
for c in iter {
1097-
s *= c;
1098-
}
1099-
s
1087+
iter.fold(Self::one(), |acc, c| acc * c)
11001088
}
11011089
}
11021090

1103-
impl<'a, T: 'a + Clone + NumAssign> Product<&'a Complex<T>> for Complex<T> {
1091+
impl<'a, T: 'a + Num + Clone> Product<&'a Complex<T>> for Complex<T> {
11041092
fn product<I>(iter: I) -> Self where I: Iterator<Item = &'a Complex<T>> {
1105-
let mut s = Self::one();
1106-
for c in iter {
1107-
s *= c;
1108-
}
1109-
s
1093+
iter.fold(Self::one(), |acc, c| acc * c)
11101094
}
11111095
}
11121096

0 commit comments

Comments
 (0)