Skip to content

Commit

Permalink
Make sum and product inherent methods on Iterator
Browse files Browse the repository at this point in the history
In addition to being nicer, this also allows you to use `sum` and `product` for
iterators yielding custom types aside from the standard integers.

Due to removing the `AdditiveIterator` and `MultiplicativeIterator` trait, this
is a breaking change.

[breaking-change]
  • Loading branch information
tbu- committed Apr 6, 2015
1 parent 8842760 commit 52bb3f7
Show file tree
Hide file tree
Showing 10 changed files with 48 additions and 159 deletions.
3 changes: 1 addition & 2 deletions src/libcollections/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ use core::clone::Clone;
use core::cmp::Ordering::{self, Greater, Less};
use core::cmp::{self, Ord, PartialEq};
use core::iter::Iterator;
use core::iter::MultiplicativeIterator;
use core::marker::Sized;
use core::mem::size_of;
use core::mem;
Expand Down Expand Up @@ -1182,7 +1181,7 @@ impl Iterator for ElementSwaps {
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
// For a vector of size n, there are exactly n! permutations.
let n = (2..self.sdir.len() + 1).product();
let n: usize = (2..self.sdir.len() + 1).product();
(n - self.swaps_made, Some(n - self.swaps_made))
}
}
Expand Down
1 change: 0 additions & 1 deletion src/libcollections/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ use self::RecompositionState::*;
use self::DecompositionType::*;

use core::clone::Clone;
use core::iter::AdditiveIterator;
use core::iter::{Iterator, Extend};
use core::option::Option::{self, Some, None};
use core::result::Result;
Expand Down
1 change: 0 additions & 1 deletion src/libcollectionstest/str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
// except according to those terms.

use std::cmp::Ordering::{Equal, Greater, Less};
use std::iter::AdditiveIterator;
use std::str::{Utf8Error, from_utf8};

#[test]
Expand Down
189 changes: 42 additions & 147 deletions src/libcore/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ use default::Default;
use marker;
use mem;
use num::{Int, Zero, One};
use ops::{self, Add, Sub, FnMut, RangeFrom};
use ops::{self, Add, Sub, FnMut, Mul, RangeFrom};
use option::Option::{self, Some, None};
use marker::Sized;
use usize;
Expand Down Expand Up @@ -489,7 +489,6 @@ pub trait Iterator {
///
/// ```
/// # #![feature(core)]
/// use std::iter::AdditiveIterator;
///
/// let a = [1, 4, 2, 3, 8, 9, 6];
/// let sum = a.iter()
Expand Down Expand Up @@ -1022,6 +1021,47 @@ pub trait Iterator {
}
}
}

/// Iterates over the entire iterator, summing up all the elements
///
/// # Examples
///
/// ```
/// # #![feature(core)]
///
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter().cloned();
/// assert!(it.sum() == 15);
/// ```
#[unstable(feature="core")]
fn sum<T, S=T>(self) -> S where
S: Add<T, Output=S> + Zero,
Self: Sized + Iterator<Item=T>
{
self.fold(Zero::zero(), |s, e| s + e)
}

/// Iterates over the entire iterator, multiplying all the elements
///
/// # Examples
///
/// ```
/// # #![feature(core)]
///
/// fn factorial(n: u32) -> u32 {
/// (1..).take_while(|&i| i <= n).product()
/// }
/// assert!(factorial(0) == 1);
/// assert!(factorial(1) == 1);
/// assert!(factorial(5) == 120);
/// ```
#[unstable(feature="core")]
fn product<T, P=T>(self) -> P where
P: Mul<T, Output=P> + One,
Self: Sized + Iterator<Item=T>
{
self.fold(One::one(), |p, e| p * e)
}
}

#[stable(feature = "rust1", since = "1.0.0")]
Expand Down Expand Up @@ -1222,151 +1262,6 @@ impl<I> RandomAccessIterator for Rev<I>
}
}

/// A trait for iterators over elements which can be added together
#[unstable(feature = "core",
reason = "needs to be re-evaluated as part of numerics reform")]
pub trait AdditiveIterator {
/// The result of summing over the iterator.
type SumResult;

/// Iterates over the entire iterator, summing up all the elements
///
/// # Examples
///
/// ```
/// # #![feature(core)]
/// use std::iter::AdditiveIterator;
///
/// let a = [1, 2, 3, 4, 5];
/// let mut it = a.iter().cloned();
/// assert!(it.sum() == 15);
/// ```
fn sum(self) -> Self::SumResult;
}

/// The sum operation of an iterator's item type. Implementing this allows
/// calling `.sum()` on the iterator.
#[unstable(feature = "core", reason = "trait is experimental")]
pub trait AdditiveIteratorItem {
/// The type of the intermediate sums.
type SumResult;
/// The start value of the sum, usually something like `0`.
fn start() -> Self::SumResult;
/// Adds another element of the iterator to the intermediate sum.
fn combine(self, other: Self::SumResult) -> Self::SumResult;
}

#[unstable(feature = "core", reason = "trait is experimental")]
impl<I: Iterator> AdditiveIterator for I where
<I as Iterator>::Item: AdditiveIteratorItem
{
type SumResult = <<I as Iterator>::Item as AdditiveIteratorItem>::SumResult;
fn sum(self) -> <I as AdditiveIterator>::SumResult {
let mut sum = <<I as Iterator>::Item as AdditiveIteratorItem>::start();
for x in self {
sum = x.combine(sum);
}
sum
}
}

macro_rules! impl_additive {
($T:ty, $init:expr) => {
#[unstable(feature = "core", reason = "trait is experimental")]
impl AdditiveIteratorItem for $T {
type SumResult = $T;
fn start() -> $T { $init }
fn combine(self, other: $T) -> $T { self + other }
}
};
}
impl_additive! { i8, 0 }
impl_additive! { i16, 0 }
impl_additive! { i32, 0 }
impl_additive! { i64, 0 }
impl_additive! { isize, 0 }
impl_additive! { u8, 0 }
impl_additive! { u16, 0 }
impl_additive! { u32, 0 }
impl_additive! { u64, 0 }
impl_additive! { usize, 0 }
impl_additive! { f32, 0.0 }
impl_additive! { f64, 0.0 }

/// A trait for iterators over elements which can be multiplied together.
#[unstable(feature = "core",
reason = "needs to be re-evaluated as part of numerics reform")]
pub trait MultiplicativeIterator {
/// The result of multiplying the elements of the iterator.
type ProductResult;

/// Iterates over the entire iterator, multiplying all the elements
///
/// # Examples
///
/// ```
/// # #![feature(core)]
/// use std::iter::MultiplicativeIterator;
///
/// fn factorial(n: usize) -> usize {
/// (1..).take_while(|&i| i <= n).product()
/// }
/// assert!(factorial(0) == 1);
/// assert!(factorial(1) == 1);
/// assert!(factorial(5) == 120);
/// ```
fn product(self) -> Self::ProductResult;
}

/// The product operation of an iterator's item type. Implementing this allows
/// calling `.product()` on the iterator.
#[unstable(feature = "core", reason = "trait is experimental")]
pub trait MultiplicativeIteratorItem {
/// The type of the intermediate products.
type ProductResult;
/// The start value of the product, usually something like `1`.
fn start() -> Self::ProductResult;
/// Multiplies another element of the iterator to the intermediate product.
fn combine(self, other: Self::ProductResult) -> Self::ProductResult;
}

#[unstable(feature = "core", reason = "trait is experimental")]
impl<I: Iterator> MultiplicativeIterator for I where
<I as Iterator>::Item: MultiplicativeIteratorItem
{
type ProductResult = <<I as Iterator>::Item as MultiplicativeIteratorItem>::ProductResult;
fn product(self) -> <I as MultiplicativeIterator>::ProductResult {
let mut product = <<I as Iterator>::Item as MultiplicativeIteratorItem>::start();
for x in self {
product = x.combine(product);
}
product
}
}

macro_rules! impl_multiplicative {
($T:ty, $init:expr) => {
#[unstable(feature = "core", reason = "trait is experimental")]
impl MultiplicativeIteratorItem for $T {
type ProductResult = $T;
fn start() -> $T { $init }
fn combine(self, other: $T) -> $T { self * other }
}
};
}
impl_multiplicative! { i8, 1 }
impl_multiplicative! { i16, 1 }
impl_multiplicative! { i32, 1 }
impl_multiplicative! { i64, 1 }
impl_multiplicative! { isize, 1 }
impl_multiplicative! { u8, 1 }
impl_multiplicative! { u16, 1 }
impl_multiplicative! { u32, 1 }
impl_multiplicative! { u64, 1 }
impl_multiplicative! { usize, 1 }
impl_multiplicative! { f32, 1.0 }
impl_multiplicative! { f64, 1.0 }

/// `MinMaxResult` is an enum returned by `min_max`. See `Iterator::min_max` for
/// more detail.
#[derive(Clone, PartialEq, Debug)]
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/check_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use middle::ty::*;
use middle::ty;
use std::cmp::Ordering;
use std::fmt;
use std::iter::{range_inclusive, AdditiveIterator, FromIterator, IntoIterator, repeat};
use std::iter::{range_inclusive, FromIterator, IntoIterator, repeat};
use std::slice;
use syntax::ast::{self, DUMMY_NODE_ID, NodeId, Pat};
use syntax::ast_util;
Expand Down
1 change: 0 additions & 1 deletion src/librustc_trans/trans/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,6 @@ use util::ppaux::{Repr, vec_map_to_string};

use std;
use std::cmp::Ordering;
use std::iter::AdditiveIterator;
use std::rc::Rc;
use syntax::ast;
use syntax::ast::{DUMMY_NODE_ID, Ident, NodeId};
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_typeck/astconv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
use util::common::{ErrorReported, FN_OUTPUT_NAME};
use util::ppaux::{self, Repr, UserString};

use std::iter::{repeat, AdditiveIterator};
use std::iter::repeat;
use std::rc::Rc;
use std::slice;
use syntax::{abi, ast, ast_util};
Expand Down
3 changes: 1 addition & 2 deletions src/libstd/old_path/posix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd};
use fmt;
use hash;
use old_io::Writer;
use iter::{AdditiveIterator, Extend};
use iter::{Iterator, Map};
use iter::{Extend, Iterator, Map};
use marker::Sized;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
Expand Down
3 changes: 1 addition & 2 deletions src/libstd/old_path/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd};
use fmt;
use hash;
use old_io::Writer;
use iter::{AdditiveIterator, Extend};
use iter::{Iterator, Map, repeat};
use iter::{Extend, Iterator, Map, repeat};
use mem;
use option::Option::{self, Some, None};
use result::Result::{self, Ok, Err};
Expand Down
2 changes: 1 addition & 1 deletion src/libunicode/u_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use core::prelude::*;

use core::char;
use core::cmp;
use core::iter::{Filter, AdditiveIterator};
use core::iter::Filter;
use core::mem;
use core::slice;
use core::str::Split;
Expand Down

0 comments on commit 52bb3f7

Please sign in to comment.