1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 /*! Composable external iterators
13 The `Iterator` trait defines an interface for objects which implement iteration as a state machine.
15 Algorithms like `zip` are provided as `Iterator` implementations which wrap other objects
16 implementing the `Iterator` trait.
20 #[allow(default_methods)]; // still off by default in stage0
25 use option::{Option, Some, None};
31 /// Conversion from an `Iterator`
32 pub trait FromIterator<A, T: Iterator<A>> {
33 /// Build a container with elements from an external iterator.
34 pub fn from_iterator(iterator: &mut T) -> Self;
37 /// An interface for dealing with "external iterators". These types of iterators
38 /// can be resumed at any time as all state is stored internally as opposed to
39 /// being located on the call stack.
40 pub trait Iterator<A> {
41 /// Advance the iterator and return the next value. Return `None` when the end is reached.
42 fn next(&mut self) -> Option<A>;
44 /// Return a lower bound and upper bound on the remaining length of the iterator.
46 /// The common use case for the estimate is pre-allocating space to store the results.
47 fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
50 /// A range iterator able to yield elements from both ends
51 pub trait DoubleEndedIterator<A>: Iterator<A> {
52 /// Yield an element from the end of the range, returning `None` if the range is empty.
53 fn next_back(&mut self) -> Option<A>;
56 /// Iterator adaptors provided for every `DoubleEndedIterator` implementation.
58 /// In the future these will be default methods instead of a utility trait.
59 pub trait DoubleEndedIteratorUtil<A> {
60 /// Flip the direction of the iterator
61 fn invert(self) -> InvertIterator<A, Self>;
64 /// Iterator adaptors provided for every `DoubleEndedIterator` implementation.
66 /// In the future these will be default methods instead of a utility trait.
67 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIteratorUtil<A> for T {
68 /// Flip the direction of the iterator
70 fn invert(self) -> InvertIterator<A, T> {
71 InvertIterator{iter: self}
75 /// An double-ended iterator with the direction inverted
76 // FIXME #6967: Dummy A parameter to get around type inference bug
78 pub struct InvertIterator<A, T> {
82 impl<A, T: DoubleEndedIterator<A>> Iterator<A> for InvertIterator<A, T> {
84 fn next(&mut self) -> Option<A> { self.iter.next_back() }
86 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
89 impl<A, T: Iterator<A>> DoubleEndedIterator<A> for InvertIterator<A, T> {
91 fn next_back(&mut self) -> Option<A> { self.iter.next() }
94 /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
95 /// implementations of the `Iterator` trait.
97 /// In the future these will be default methods instead of a utility trait.
98 pub trait IteratorUtil<A> {
99 /// Chain this iterator with another, returning a new iterator which will
100 /// finish iterating over the current iterator, and then it will iterate
101 /// over the other specified iterator.
108 /// let mut it = a.iter().chain_(b.iter());
109 /// assert_eq!(it.next().get(), &0);
110 /// assert_eq!(it.next().get(), &1);
111 /// assert!(it.next().is_none());
113 fn chain_<U: Iterator<A>>(self, other: U) -> ChainIterator<A, Self, U>;
115 /// Creates an iterator which iterates over both this and the specified
116 /// iterators simultaneously, yielding the two elements as pairs. When
117 /// either iterator returns None, all further invocations of next() will
125 /// let mut it = a.iter().zip(b.iter());
126 /// assert_eq!(it.next().get(), (&0, &1));
127 /// assert!(it.next().is_none());
129 fn zip<B, U: Iterator<B>>(self, other: U) -> ZipIterator<A, Self, B, U>;
131 // FIXME: #5898: should be called map
132 /// Creates a new iterator which will apply the specified function to each
133 /// element returned by the first, yielding the mapped element instead.
139 /// let mut it = a.iter().transform(|&x| 2 * x);
140 /// assert_eq!(it.next().get(), 2);
141 /// assert_eq!(it.next().get(), 4);
142 /// assert!(it.next().is_none());
144 fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, Self>;
146 /// Creates an iterator which applies the predicate to each element returned
147 /// by this iterator. Only elements which have the predicate evaluate to
148 /// `true` will be yielded.
154 /// let mut it = a.iter().filter(|&x| *x > 1);
155 /// assert_eq!(it.next().get(), &2);
156 /// assert!(it.next().is_none());
158 fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> FilterIterator<'r, A, Self>;
160 /// Creates an iterator which both filters and maps elements.
161 /// If the specified function returns None, the element is skipped.
162 /// Otherwise the option is unwrapped and the new value is yielded.
168 /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
169 /// assert_eq!(it.next().get(), 4);
170 /// assert!(it.next().is_none());
172 fn filter_map<'r, B>(self, f: &'r fn(A) -> Option<B>) -> FilterMapIterator<'r, A, B, Self>;
174 /// Creates an iterator which yields a pair of the value returned by this
175 /// iterator plus the current index of iteration.
180 /// let a = [100, 200];
181 /// let mut it = a.iter().enumerate();
182 /// assert_eq!(it.next().get(), (0, &100));
183 /// assert_eq!(it.next().get(), (1, &200));
184 /// assert!(it.next().is_none());
186 fn enumerate(self) -> EnumerateIterator<A, Self>;
188 /// Creates an iterator which invokes the predicate on elements until it
189 /// returns false. Once the predicate returns false, all further elements are
195 /// let a = [1, 2, 3, 2, 1];
196 /// let mut it = a.iter().skip_while(|&a| *a < 3);
197 /// assert_eq!(it.next().get(), &3);
198 /// assert_eq!(it.next().get(), &2);
199 /// assert_eq!(it.next().get(), &1);
200 /// assert!(it.next().is_none());
202 fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) -> SkipWhileIterator<'r, A, Self>;
204 /// Creates an iterator which yields elements so long as the predicate
205 /// returns true. After the predicate returns false for the first time, no
206 /// further elements will be yielded.
211 /// let a = [1, 2, 3, 2, 1];
212 /// let mut it = a.iter().take_while(|&a| *a < 3);
213 /// assert_eq!(it.next().get(), &1);
214 /// assert_eq!(it.next().get(), &2);
215 /// assert!(it.next().is_none());
217 fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) -> TakeWhileIterator<'r, A, Self>;
219 /// Creates an iterator which skips the first `n` elements of this iterator,
220 /// and then it yields all further items.
225 /// let a = [1, 2, 3, 4, 5];
226 /// let mut it = a.iter().skip(3);
227 /// assert_eq!(it.next().get(), &4);
228 /// assert_eq!(it.next().get(), &5);
229 /// assert!(it.next().is_none());
231 fn skip(self, n: uint) -> SkipIterator<A, Self>;
233 // FIXME: #5898: should be called take
234 /// Creates an iterator which yields the first `n` elements of this
235 /// iterator, and then it will always return None.
240 /// let a = [1, 2, 3, 4, 5];
241 /// let mut it = a.iter().take_(3);
242 /// assert_eq!(it.next().get(), &1);
243 /// assert_eq!(it.next().get(), &2);
244 /// assert_eq!(it.next().get(), &3);
245 /// assert!(it.next().is_none());
247 fn take_(self, n: uint) -> TakeIterator<A, Self>;
249 /// Creates a new iterator which behaves in a similar fashion to foldl.
250 /// There is a state which is passed between each iteration and can be
251 /// mutated as necessary. The yielded values from the closure are yielded
252 /// from the ScanIterator instance when not None.
257 /// let a = [1, 2, 3, 4, 5];
258 /// let mut it = a.iter().scan(1, |fac, &x| {
262 /// assert_eq!(it.next().get(), 1);
263 /// assert_eq!(it.next().get(), 2);
264 /// assert_eq!(it.next().get(), 6);
265 /// assert_eq!(it.next().get(), 24);
266 /// assert_eq!(it.next().get(), 120);
267 /// assert!(it.next().is_none());
269 fn scan<'r, St, B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option<B>)
270 -> ScanIterator<'r, A, B, Self, St>;
272 /// Creates an iterator that maps each element to an iterator,
273 /// and yields the elements of the produced iterators
278 /// let xs = [2u, 3];
279 /// let ys = [0u, 1, 0, 1, 2];
280 /// let mut it = xs.iter().flat_map_(|&x| Counter::new(0u, 1).take_(x));
281 /// // Check that `it` has the same elements as `ys`
283 /// for it.advance |x: uint| {
284 /// assert_eq!(x, ys[i]);
288 // FIXME: #5898: should be called `flat_map`
289 fn flat_map_<'r, B, U: Iterator<B>>(self, f: &'r fn(A) -> U)
290 -> FlatMapIterator<'r, A, B, Self, U>;
292 /// Creates an iterator that calls a function with a reference to each
293 /// element before yielding it. This is often useful for debugging an
294 /// iterator pipeline.
299 ///let xs = [1u, 4, 2, 3, 8, 9, 6];
300 ///let sum = xs.iter()
301 /// .transform(|&x| x)
302 /// .peek_(|&x| debug!("filtering %u", x))
303 /// .filter(|&x| x % 2 == 0)
304 /// .peek_(|&x| debug!("%u made it through", x))
306 ///println(sum.to_str());
308 // FIXME: #5898: should be called `peek`
309 fn peek_<'r>(self, f: &'r fn(&A)) -> PeekIterator<'r, A, Self>;
311 /// An adaptation of an external iterator to the for-loop protocol of rust.
316 /// use std::iterator::Counter;
318 /// for Counter::new(0, 10).advance |i| {
319 /// io::println(fmt!("%d", i));
322 fn advance(&mut self, f: &fn(A) -> bool) -> bool;
324 /// Loops through the entire iterator, collecting all of the elements into
325 /// a container implementing `FromIterator`.
330 /// let a = [1, 2, 3, 4, 5];
331 /// let b: ~[int] = a.iter().transform(|&x| x).collect();
334 fn collect<B: FromIterator<A, Self>>(&mut self) -> B;
336 /// Loops through `n` iterations, returning the `n`th element of the
342 /// let a = [1, 2, 3, 4, 5];
343 /// let mut it = a.iter();
344 /// assert!(it.nth(2).get() == &3);
345 /// assert!(it.nth(2) == None);
347 fn nth(&mut self, n: uint) -> Option<A>;
349 /// Loops through the entire iterator, returning the last element of the
355 /// let a = [1, 2, 3, 4, 5];
356 /// assert!(a.iter().last().get() == &5);
358 // FIXME: #5898: should be called `last`
359 fn last_(&mut self) -> Option<A>;
361 /// Performs a fold operation over the entire iterator, returning the
362 /// eventual state at the end of the iteration.
367 /// let a = [1, 2, 3, 4, 5];
368 /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
370 fn fold<B>(&mut self, start: B, f: &fn(B, A) -> B) -> B;
372 // FIXME: #5898: should be called len
373 /// Counts the number of elements in this iterator.
378 /// let a = [1, 2, 3, 4, 5];
379 /// let mut it = a.iter();
380 /// assert!(it.len_() == 5);
381 /// assert!(it.len_() == 0);
383 fn len_(&mut self) -> uint;
385 /// Tests whether the predicate holds true for all elements in the iterator.
390 /// let a = [1, 2, 3, 4, 5];
391 /// assert!(a.iter().all(|&x| *x > 0));
392 /// assert!(!a.iter().all(|&x| *x > 2));
394 fn all(&mut self, f: &fn(A) -> bool) -> bool;
396 /// Tests whether any element of an iterator satisfies the specified
402 /// let a = [1, 2, 3, 4, 5];
403 /// let mut it = a.iter();
404 /// assert!(it.any(|&x| *x == 3));
405 /// assert!(!it.any(|&x| *x == 3));
407 fn any(&mut self, f: &fn(A) -> bool) -> bool;
409 /// Return the first element satisfying the specified predicate
410 fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A>;
412 /// Return the index of the first element satisfying the specified predicate
413 fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint>;
415 /// Count the number of elements satisfying the specified predicate
416 fn count(&mut self, predicate: &fn(A) -> bool) -> uint;
418 /// Return the element that gives the maximum value from the specfied function
423 /// let xs = [-3, 0, 1, 5, -10];
424 /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
426 fn max_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>;
428 /// Return the element that gives the minimum value from the specfied function
433 /// let xs = [-3, 0, 1, 5, -10];
434 /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
436 fn min_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A>;
439 /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
440 /// implementations of the `Iterator` trait.
442 /// In the future these will be default methods instead of a utility trait.
443 impl<A, T: Iterator<A>> IteratorUtil<A> for T {
445 fn chain_<U: Iterator<A>>(self, other: U) -> ChainIterator<A, T, U> {
446 ChainIterator{a: self, b: other, flag: false}
450 fn zip<B, U: Iterator<B>>(self, other: U) -> ZipIterator<A, T, B, U> {
451 ZipIterator{a: self, b: other}
454 // FIXME: #5898: should be called map
456 fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, T> {
457 MapIterator{iter: self, f: f}
461 fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> FilterIterator<'r, A, T> {
462 FilterIterator{iter: self, predicate: predicate}
466 fn filter_map<'r, B>(self, f: &'r fn(A) -> Option<B>) -> FilterMapIterator<'r, A, B, T> {
467 FilterMapIterator { iter: self, f: f }
471 fn enumerate(self) -> EnumerateIterator<A, T> {
472 EnumerateIterator{iter: self, count: 0}
476 fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) -> SkipWhileIterator<'r, A, T> {
477 SkipWhileIterator{iter: self, flag: false, predicate: predicate}
481 fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) -> TakeWhileIterator<'r, A, T> {
482 TakeWhileIterator{iter: self, flag: false, predicate: predicate}
486 fn skip(self, n: uint) -> SkipIterator<A, T> {
487 SkipIterator{iter: self, n: n}
490 // FIXME: #5898: should be called take
492 fn take_(self, n: uint) -> TakeIterator<A, T> {
493 TakeIterator{iter: self, n: n}
497 fn scan<'r, St, B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option<B>)
498 -> ScanIterator<'r, A, B, T, St> {
499 ScanIterator{iter: self, f: f, state: initial_state}
503 fn flat_map_<'r, B, U: Iterator<B>>(self, f: &'r fn(A) -> U)
504 -> FlatMapIterator<'r, A, B, T, U> {
505 FlatMapIterator{iter: self, f: f, subiter: None }
508 // FIXME: #5898: should be called `peek`
510 fn peek_<'r>(self, f: &'r fn(&A)) -> PeekIterator<'r, A, T> {
511 PeekIterator{iter: self, f: f}
514 /// A shim implementing the `for` loop iteration protocol for iterator objects
516 fn advance(&mut self, f: &fn(A) -> bool) -> bool {
520 if !f(x) { return false; }
522 None => { return true; }
528 fn collect<B: FromIterator<A, T>>(&mut self) -> B {
529 FromIterator::from_iterator(self)
532 /// Return the `n`th item yielded by an iterator.
534 fn nth(&mut self, mut n: uint) -> Option<A> {
537 Some(x) => if n == 0 { return Some(x) },
544 /// Return the last item yielded by an iterator.
546 fn last_(&mut self) -> Option<A> {
548 for self.advance |x| { last = Some(x); }
552 /// Reduce an iterator to an accumulated value
554 fn fold<B>(&mut self, init: B, f: &fn(B, A) -> B) -> B {
555 let mut accum = init;
558 Some(x) => { accum = f(accum, x); }
565 /// Count the number of items yielded by an iterator
567 fn len_(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) }
570 fn all(&mut self, f: &fn(A) -> bool) -> bool {
571 for self.advance |x| { if !f(x) { return false; } }
576 fn any(&mut self, f: &fn(A) -> bool) -> bool {
577 for self.advance |x| { if f(x) { return true; } }
581 /// Return the first element satisfying the specified predicate
583 fn find_(&mut self, predicate: &fn(&A) -> bool) -> Option<A> {
584 for self.advance |x| {
585 if predicate(&x) { return Some(x) }
590 /// Return the index of the first element satisfying the specified predicate
592 fn position(&mut self, predicate: &fn(A) -> bool) -> Option<uint> {
594 for self.advance |x| {
604 fn count(&mut self, predicate: &fn(A) -> bool) -> uint {
606 for self.advance |x| {
607 if predicate(x) { i += 1 }
613 fn max_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A> {
614 self.fold(None, |max: Option<(A, B)>, x| {
617 None => Some((x, x_val)),
618 Some((y, y_val)) => if x_val > y_val {
624 }).map_consume(|(x, _)| x)
628 fn min_by<B: Ord>(&mut self, f: &fn(&A) -> B) -> Option<A> {
629 self.fold(None, |min: Option<(A, B)>, x| {
632 None => Some((x, x_val)),
633 Some((y, y_val)) => if x_val < y_val {
639 }).map_consume(|(x, _)| x)
643 /// A trait for iterators over elements which can be added together
644 pub trait AdditiveIterator<A> {
645 /// Iterates over the entire iterator, summing up all the elements
650 /// let a = [1, 2, 3, 4, 5];
651 /// let mut it = a.iter().transform(|&x| x);
652 /// assert!(it.sum() == 15);
654 fn sum(&mut self) -> A;
657 impl<A: Add<A, A> + Zero, T: Iterator<A>> AdditiveIterator<A> for T {
659 fn sum(&mut self) -> A { self.fold(Zero::zero::<A>(), |s, x| s + x) }
662 /// A trait for iterators over elements whose elements can be multiplied
664 pub trait MultiplicativeIterator<A> {
665 /// Iterates over the entire iterator, multiplying all the elements
670 /// use std::iterator::Counter;
672 /// fn factorial(n: uint) -> uint {
673 /// Counter::new(1u, 1).take_while(|&i| i <= n).product()
675 /// assert!(factorial(0) == 1);
676 /// assert!(factorial(1) == 1);
677 /// assert!(factorial(5) == 120);
679 fn product(&mut self) -> A;
682 impl<A: Mul<A, A> + One, T: Iterator<A>> MultiplicativeIterator<A> for T {
684 fn product(&mut self) -> A { self.fold(One::one::<A>(), |p, x| p * x) }
687 /// A trait for iterators over elements which can be compared to one another.
688 /// The type of each element must ascribe to the `Ord` trait.
689 pub trait OrdIterator<A> {
690 /// Consumes the entire iterator to return the maximum element.
695 /// let a = [1, 2, 3, 4, 5];
696 /// assert!(a.iter().max().get() == &5);
698 fn max(&mut self) -> Option<A>;
700 /// Consumes the entire iterator to return the minimum element.
705 /// let a = [1, 2, 3, 4, 5];
706 /// assert!(a.iter().min().get() == &1);
708 fn min(&mut self) -> Option<A>;
711 impl<A: Ord, T: Iterator<A>> OrdIterator<A> for T {
713 fn max(&mut self) -> Option<A> {
714 self.fold(None, |max, x| {
717 Some(y) => Some(cmp::max(x, y))
723 fn min(&mut self) -> Option<A> {
724 self.fold(None, |min, x| {
727 Some(y) => Some(cmp::min(x, y))
733 /// A trait for iterators that are clonable.
734 // FIXME #6967: Dummy A parameter to get around type inference bug
735 pub trait ClonableIterator<A> {
736 /// Repeats an iterator endlessly
741 /// let a = Counter::new(1,1).take_(1);
742 /// let mut cy = a.cycle();
743 /// assert_eq!(cy.next(), Some(1));
744 /// assert_eq!(cy.next(), Some(1));
746 fn cycle(self) -> CycleIterator<A, Self>;
749 impl<A, T: Clone + Iterator<A>> ClonableIterator<A> for T {
751 fn cycle(self) -> CycleIterator<A, T> {
752 CycleIterator{orig: self.clone(), iter: self}
756 /// An iterator that repeats endlessly
758 pub struct CycleIterator<A, T> {
763 impl<A, T: Clone + Iterator<A>> Iterator<A> for CycleIterator<A, T> {
765 fn next(&mut self) -> Option<A> {
766 match self.iter.next() {
767 None => { self.iter = self.orig.clone(); self.iter.next() }
773 fn size_hint(&self) -> (uint, Option<uint>) {
774 // the cycle iterator is either empty or infinite
775 match self.orig.size_hint() {
776 sz @ (0, Some(0)) => sz,
778 _ => (uint::max_value, None)
783 /// An iterator which strings two iterators together
784 // FIXME #6967: Dummy A parameter to get around type inference bug
786 pub struct ChainIterator<A, T, U> {
792 impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for ChainIterator<A, T, U> {
794 fn next(&mut self) -> Option<A> {
798 match self.a.next() {
799 Some(x) => return Some(x),
808 fn size_hint(&self) -> (uint, Option<uint>) {
809 let (a_lower, a_upper) = self.a.size_hint();
810 let (b_lower, b_upper) = self.b.size_hint();
812 let lower = if uint::max_value - a_lower < b_lower {
818 let upper = match (a_upper, b_upper) {
819 (Some(x), Some(y)) if uint::max_value - x < y => Some(uint::max_value),
820 (Some(x), Some(y)) => Some(x + y),
828 impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
829 for ChainIterator<A, T, U> {
831 fn next_back(&mut self) -> Option<A> {
832 match self.b.next_back() {
834 None => self.a.next_back()
839 /// An iterator which iterates two other iterators simultaneously
840 // FIXME #6967: Dummy A & B parameters to get around type inference bug
842 pub struct ZipIterator<A, T, B, U> {
847 impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for ZipIterator<A, T, B, U> {
849 fn next(&mut self) -> Option<(A, B)> {
850 match (self.a.next(), self.b.next()) {
851 (Some(x), Some(y)) => Some((x, y)),
857 fn size_hint(&self) -> (uint, Option<uint>) {
858 let (a_lower, a_upper) = self.a.size_hint();
859 let (b_lower, b_upper) = self.b.size_hint();
861 let lower = cmp::min(a_lower, b_lower);
863 let upper = match (a_upper, b_upper) {
864 (Some(x), Some(y)) => Some(cmp::min(x,y)),
865 (Some(x), None) => Some(x),
866 (None, Some(y)) => Some(y),
874 /// An iterator which maps the values of `iter` with `f`
875 pub struct MapIterator<'self, A, B, T> {
877 priv f: &'self fn(A) -> B
880 impl<'self, A, B, T: Iterator<A>> Iterator<B> for MapIterator<'self, A, B, T> {
882 fn next(&mut self) -> Option<B> {
883 match self.iter.next() {
884 Some(a) => Some((self.f)(a)),
890 fn size_hint(&self) -> (uint, Option<uint>) {
891 self.iter.size_hint()
895 impl<'self, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
896 for MapIterator<'self, A, B, T> {
898 fn next_back(&mut self) -> Option<B> {
899 match self.iter.next_back() {
900 Some(a) => Some((self.f)(a)),
906 /// An iterator which filters the elements of `iter` with `predicate`
907 pub struct FilterIterator<'self, A, T> {
909 priv predicate: &'self fn(&A) -> bool
912 impl<'self, A, T: Iterator<A>> Iterator<A> for FilterIterator<'self, A, T> {
914 fn next(&mut self) -> Option<A> {
915 for self.iter.advance |x| {
916 if (self.predicate)(&x) {
926 fn size_hint(&self) -> (uint, Option<uint>) {
927 let (_, upper) = self.iter.size_hint();
928 (0, upper) // can't know a lower bound, due to the predicate
932 impl<'self, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for FilterIterator<'self, A, T> {
934 fn next_back(&mut self) -> Option<A> {
936 match self.iter.next_back() {
939 if (self.predicate)(&x) {
950 /// An iterator which uses `f` to both filter and map elements from `iter`
951 pub struct FilterMapIterator<'self, A, B, T> {
953 priv f: &'self fn(A) -> Option<B>
956 impl<'self, A, B, T: Iterator<A>> Iterator<B> for FilterMapIterator<'self, A, B, T> {
958 fn next(&mut self) -> Option<B> {
959 for self.iter.advance |x| {
961 Some(y) => return Some(y),
969 fn size_hint(&self) -> (uint, Option<uint>) {
970 let (_, upper) = self.iter.size_hint();
971 (0, upper) // can't know a lower bound, due to the predicate
975 impl<'self, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
976 for FilterMapIterator<'self, A, B, T> {
978 fn next_back(&mut self) -> Option<B> {
980 match self.iter.next_back() {
984 Some(y) => return Some(y),
993 /// An iterator which yields the current count and the element during iteration
994 // FIXME #6967: Dummy A parameter to get around type inference bug
996 pub struct EnumerateIterator<A, T> {
1001 impl<A, T: Iterator<A>> Iterator<(uint, A)> for EnumerateIterator<A, T> {
1003 fn next(&mut self) -> Option<(uint, A)> {
1004 match self.iter.next() {
1006 let ret = Some((self.count, a));
1015 fn size_hint(&self) -> (uint, Option<uint>) {
1016 self.iter.size_hint()
1020 /// An iterator which rejects elements while `predicate` is true
1021 pub struct SkipWhileIterator<'self, A, T> {
1024 priv predicate: &'self fn(&A) -> bool
1027 impl<'self, A, T: Iterator<A>> Iterator<A> for SkipWhileIterator<'self, A, T> {
1029 fn next(&mut self) -> Option<A> {
1030 let mut next = self.iter.next();
1037 if (self.predicate)(&x) {
1038 next = self.iter.next();
1052 fn size_hint(&self) -> (uint, Option<uint>) {
1053 let (_, upper) = self.iter.size_hint();
1054 (0, upper) // can't know a lower bound, due to the predicate
1058 /// An iterator which only accepts elements while `predicate` is true
1059 pub struct TakeWhileIterator<'self, A, T> {
1062 priv predicate: &'self fn(&A) -> bool
1065 impl<'self, A, T: Iterator<A>> Iterator<A> for TakeWhileIterator<'self, A, T> {
1067 fn next(&mut self) -> Option<A> {
1071 match self.iter.next() {
1073 if (self.predicate)(&x) {
1086 fn size_hint(&self) -> (uint, Option<uint>) {
1087 let (_, upper) = self.iter.size_hint();
1088 (0, upper) // can't know a lower bound, due to the predicate
1092 /// An iterator which skips over `n` elements of `iter`.
1093 // FIXME #6967: Dummy A parameter to get around type inference bug
1095 pub struct SkipIterator<A, T> {
1100 impl<A, T: Iterator<A>> Iterator<A> for SkipIterator<A, T> {
1102 fn next(&mut self) -> Option<A> {
1103 let mut next = self.iter.next();
1111 next = self.iter.next();
1126 fn size_hint(&self) -> (uint, Option<uint>) {
1127 let (lower, upper) = self.iter.size_hint();
1129 let lower = if lower >= self.n { lower - self.n } else { 0 };
1131 let upper = match upper {
1132 Some(x) if x >= self.n => Some(x - self.n),
1141 /// An iterator which only iterates over the first `n` iterations of `iter`.
1142 // FIXME #6967: Dummy A parameter to get around type inference bug
1144 pub struct TakeIterator<A, T> {
1149 impl<A, T: Iterator<A>> Iterator<A> for TakeIterator<A, T> {
1151 fn next(&mut self) -> Option<A> {
1152 let next = self.iter.next();
1162 fn size_hint(&self) -> (uint, Option<uint>) {
1163 let (lower, upper) = self.iter.size_hint();
1165 let lower = cmp::min(lower, self.n);
1167 let upper = match upper {
1168 Some(x) if x < self.n => Some(x),
1176 /// An iterator to maintain state while iterating another iterator
1177 pub struct ScanIterator<'self, A, B, T, St> {
1179 priv f: &'self fn(&mut St, A) -> Option<B>,
1181 /// The current internal state to be passed to the closure next.
1185 impl<'self, A, B, T: Iterator<A>, St> Iterator<B> for ScanIterator<'self, A, B, T, St> {
1187 fn next(&mut self) -> Option<B> {
1188 self.iter.next().chain(|a| (self.f)(&mut self.state, a))
1192 fn size_hint(&self) -> (uint, Option<uint>) {
1193 let (_, upper) = self.iter.size_hint();
1194 (0, upper) // can't know a lower bound, due to the scan function
1198 /// An iterator that maps each element to an iterator,
1199 /// and yields the elements of the produced iterators
1201 // FIXME #6967: Dummy B parameter to get around type inference bug
1202 pub struct FlatMapIterator<'self, A, B, T, U> {
1204 priv f: &'self fn(A) -> U,
1205 priv subiter: Option<U>,
1208 impl<'self, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for
1209 FlatMapIterator<'self, A, B, T, U> {
1211 fn next(&mut self) -> Option<B> {
1213 for self.subiter.mut_iter().advance |inner| {
1214 for inner.advance |x| {
1218 match self.iter.next().map_consume(|x| (self.f)(x)) {
1219 None => return None,
1220 next => self.subiter = next,
1226 /// An iterator that calls a function with a reference to each
1227 /// element before yielding it.
1228 pub struct PeekIterator<'self, A, T> {
1230 priv f: &'self fn(&A)
1233 impl<'self, A, T: Iterator<A>> Iterator<A> for PeekIterator<'self, A, T> {
1235 fn next(&mut self) -> Option<A> {
1236 let next = self.iter.next();
1239 Some(ref a) => (self.f)(a),
1247 fn size_hint(&self) -> (uint, Option<uint>) {
1248 self.iter.size_hint()
1252 impl<'self, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for PeekIterator<'self, A, T> {
1254 fn next_back(&mut self) -> Option<A> {
1255 let next = self.iter.next_back();
1258 Some(ref a) => (self.f)(a),
1266 /// An iterator which just modifies the contained state throughout iteration.
1267 pub struct UnfoldrIterator<'self, A, St> {
1268 priv f: &'self fn(&mut St) -> Option<A>,
1269 /// Internal state that will be yielded on the next iteration
1273 impl<'self, A, St> UnfoldrIterator<'self, A, St> {
1274 /// Creates a new iterator with the specified closure as the "iterator
1275 /// function" and an initial state to eventually pass to the iterator
1277 pub fn new<'a>(initial_state: St, f: &'a fn(&mut St) -> Option<A>)
1278 -> UnfoldrIterator<'a, A, St> {
1281 state: initial_state
1286 impl<'self, A, St> Iterator<A> for UnfoldrIterator<'self, A, St> {
1288 fn next(&mut self) -> Option<A> {
1289 (self.f)(&mut self.state)
1293 /// An infinite iterator starting at `start` and advancing by `step` with each
1296 pub struct Counter<A> {
1297 /// The current state the counter is at (next value to be yielded)
1299 /// The amount that this iterator is stepping by
1303 impl<A> Counter<A> {
1304 /// Creates a new counter with the specified start/step
1306 pub fn new(start: A, step: A) -> Counter<A> {
1307 Counter{state: start, step: step}
1311 impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
1313 fn next(&mut self) -> Option<A> {
1314 let result = self.state.clone();
1315 self.state = self.state.add(&self.step); // FIXME: #6050
1320 fn size_hint(&self) -> (uint, Option<uint>) {
1321 (uint::max_value, None) // Too bad we can't specify an infinite lower bound
1333 fn test_counter_from_iter() {
1334 let mut it = Counter::new(0, 5).take_(10);
1335 let xs: ~[int] = FromIterator::from_iterator(&mut it);
1336 assert_eq!(xs, ~[0, 5, 10, 15, 20, 25, 30, 35, 40, 45]);
1340 fn test_iterator_chain() {
1341 let xs = [0u, 1, 2, 3, 4, 5];
1342 let ys = [30u, 40, 50, 60];
1343 let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60];
1344 let mut it = xs.iter().chain_(ys.iter());
1346 for it.advance |&x| {
1347 assert_eq!(x, expected[i]);
1350 assert_eq!(i, expected.len());
1352 let ys = Counter::new(30u, 10).take_(4);
1353 let mut it = xs.iter().transform(|&x| x).chain_(ys);
1355 for it.advance |x| {
1356 assert_eq!(x, expected[i]);
1359 assert_eq!(i, expected.len());
1363 fn test_filter_map() {
1364 let mut it = Counter::new(0u, 1u).take_(10)
1365 .filter_map(|x| if x.is_even() { Some(x*x) } else { None });
1366 assert_eq!(it.collect::<~[uint]>(), ~[0*0, 2*2, 4*4, 6*6, 8*8]);
1370 fn test_iterator_enumerate() {
1371 let xs = [0u, 1, 2, 3, 4, 5];
1372 let mut it = xs.iter().enumerate();
1373 for it.advance |(i, &x)| {
1379 fn test_iterator_take_while() {
1380 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
1381 let ys = [0u, 1, 2, 3, 5, 13];
1382 let mut it = xs.iter().take_while(|&x| *x < 15u);
1384 for it.advance |&x| {
1385 assert_eq!(x, ys[i]);
1388 assert_eq!(i, ys.len());
1392 fn test_iterator_skip_while() {
1393 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
1394 let ys = [15, 16, 17, 19];
1395 let mut it = xs.iter().skip_while(|&x| *x < 15u);
1397 for it.advance |&x| {
1398 assert_eq!(x, ys[i]);
1401 assert_eq!(i, ys.len());
1405 fn test_iterator_skip() {
1406 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30];
1407 let ys = [13, 15, 16, 17, 19, 20, 30];
1408 let mut it = xs.iter().skip(5);
1410 for it.advance |&x| {
1411 assert_eq!(x, ys[i]);
1414 assert_eq!(i, ys.len());
1418 fn test_iterator_take() {
1419 let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19];
1420 let ys = [0u, 1, 2, 3, 5];
1421 let mut it = xs.iter().take_(5);
1423 for it.advance |&x| {
1424 assert_eq!(x, ys[i]);
1427 assert_eq!(i, ys.len());
1431 fn test_iterator_scan() {
1432 // test the type inference
1433 fn add(old: &mut int, new: &uint) -> Option<float> {
1434 *old += *new as int;
1437 let xs = [0u, 1, 2, 3, 4];
1438 let ys = [0f, 1f, 3f, 6f, 10f];
1440 let mut it = xs.iter().scan(0, add);
1442 for it.advance |x| {
1443 assert_eq!(x, ys[i]);
1446 assert_eq!(i, ys.len());
1450 fn test_iterator_flat_map() {
1451 let xs = [0u, 3, 6];
1452 let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8];
1453 let mut it = xs.iter().flat_map_(|&x| Counter::new(x, 1).take_(3));
1455 for it.advance |x: uint| {
1456 assert_eq!(x, ys[i]);
1459 assert_eq!(i, ys.len());
1464 let xs = [1u, 2, 3, 4];
1470 .collect::<~[uint]>();
1472 assert_eq!(n, xs.len());
1473 assert_eq!(xs, ys.as_slice());
1478 fn count(st: &mut uint) -> Option<uint> {
1480 let ret = Some(*st);
1488 let mut it = UnfoldrIterator::new(0, count);
1490 for it.advance |counted| {
1491 assert_eq!(counted, i);
1500 let it = Counter::new(0u,1).take_(cycle_len).cycle();
1501 assert_eq!(it.size_hint(), (uint::max_value, None));
1502 for it.take_(100).enumerate().advance |(i, x)| {
1503 assert_eq!(i % cycle_len, x);
1506 let mut it = Counter::new(0u,1).take_(0).cycle();
1507 assert_eq!(it.size_hint(), (0, Some(0)));
1508 assert_eq!(it.next(), None);
1512 fn test_iterator_nth() {
1513 let v = &[0, 1, 2, 3, 4];
1514 for uint::range(0, v.len()) |i| {
1515 assert_eq!(v.iter().nth(i).unwrap(), &v[i]);
1520 fn test_iterator_last() {
1521 let v = &[0, 1, 2, 3, 4];
1522 assert_eq!(v.iter().last_().unwrap(), &4);
1523 assert_eq!(v.slice(0, 1).iter().last_().unwrap(), &0);
1527 fn test_iterator_len() {
1528 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1529 assert_eq!(v.slice(0, 4).iter().len_(), 4);
1530 assert_eq!(v.slice(0, 10).iter().len_(), 10);
1531 assert_eq!(v.slice(0, 0).iter().len_(), 0);
1535 fn test_iterator_sum() {
1536 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1537 assert_eq!(v.slice(0, 4).iter().transform(|&x| x).sum(), 6);
1538 assert_eq!(v.iter().transform(|&x| x).sum(), 55);
1539 assert_eq!(v.slice(0, 0).iter().transform(|&x| x).sum(), 0);
1543 fn test_iterator_product() {
1544 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1545 assert_eq!(v.slice(0, 4).iter().transform(|&x| x).product(), 0);
1546 assert_eq!(v.slice(1, 5).iter().transform(|&x| x).product(), 24);
1547 assert_eq!(v.slice(0, 0).iter().transform(|&x| x).product(), 1);
1551 fn test_iterator_max() {
1552 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1553 assert_eq!(v.slice(0, 4).iter().transform(|&x| x).max(), Some(3));
1554 assert_eq!(v.iter().transform(|&x| x).max(), Some(10));
1555 assert_eq!(v.slice(0, 0).iter().transform(|&x| x).max(), None);
1559 fn test_iterator_min() {
1560 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1561 assert_eq!(v.slice(0, 4).iter().transform(|&x| x).min(), Some(0));
1562 assert_eq!(v.iter().transform(|&x| x).min(), Some(0));
1563 assert_eq!(v.slice(0, 0).iter().transform(|&x| x).min(), None);
1567 fn test_iterator_size_hint() {
1568 let c = Counter::new(0, 1);
1569 let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
1570 let v2 = &[10, 11, 12];
1573 assert_eq!(c.size_hint(), (uint::max_value, None));
1574 assert_eq!(vi.size_hint(), (10, Some(10)));
1576 assert_eq!(c.take_(5).size_hint(), (5, Some(5)));
1577 assert_eq!(c.skip(5).size_hint().second(), None);
1578 assert_eq!(c.take_while(|_| false).size_hint(), (0, None));
1579 assert_eq!(c.skip_while(|_| false).size_hint(), (0, None));
1580 assert_eq!(c.enumerate().size_hint(), (uint::max_value, None));
1581 assert_eq!(c.chain_(vi.transform(|&i| i)).size_hint(), (uint::max_value, None));
1582 assert_eq!(c.zip(vi).size_hint(), (10, Some(10)));
1583 assert_eq!(c.scan(0, |_,_| Some(0)).size_hint(), (0, None));
1584 assert_eq!(c.filter(|_| false).size_hint(), (0, None));
1585 assert_eq!(c.transform(|_| 0).size_hint(), (uint::max_value, None));
1586 assert_eq!(c.filter_map(|_| Some(0)).size_hint(), (0, None));
1588 assert_eq!(vi.take_(5).size_hint(), (5, Some(5)));
1589 assert_eq!(vi.take_(12).size_hint(), (10, Some(10)));
1590 assert_eq!(vi.skip(3).size_hint(), (7, Some(7)));
1591 assert_eq!(vi.skip(12).size_hint(), (0, Some(0)));
1592 assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10)));
1593 assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10)));
1594 assert_eq!(vi.enumerate().size_hint(), (10, Some(10)));
1595 assert_eq!(vi.chain_(v2.iter()).size_hint(), (13, Some(13)));
1596 assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3)));
1597 assert_eq!(vi.scan(0, |_,_| Some(0)).size_hint(), (0, Some(10)));
1598 assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10)));
1599 assert_eq!(vi.transform(|i| i+1).size_hint(), (10, Some(10)));
1600 assert_eq!(vi.filter_map(|_| Some(0)).size_hint(), (0, Some(10)));
1605 let a = ~[1, 2, 3, 4, 5];
1606 let b: ~[int] = a.iter().transform(|&x| x).collect();
1612 let v = ~&[1, 2, 3, 4, 5];
1613 assert!(v.iter().all(|&x| x < 10));
1614 assert!(!v.iter().all(|&x| x.is_even()));
1615 assert!(!v.iter().all(|&x| x > 100));
1616 assert!(v.slice(0, 0).iter().all(|_| fail!()));
1621 let v = ~&[1, 2, 3, 4, 5];
1622 assert!(v.iter().any(|&x| x < 10));
1623 assert!(v.iter().any(|&x| x.is_even()));
1624 assert!(!v.iter().any(|&x| x > 100));
1625 assert!(!v.slice(0, 0).iter().any(|_| fail!()));
1630 let v = &[1, 3, 9, 27, 103, 14, 11];
1631 assert_eq!(*v.iter().find_(|x| *x & 1 == 0).unwrap(), 14);
1632 assert_eq!(*v.iter().find_(|x| *x % 3 == 0).unwrap(), 3);
1633 assert!(v.iter().find_(|x| *x % 12 == 0).is_none());
1637 fn test_position() {
1638 let v = &[1, 3, 9, 27, 103, 14, 11];
1639 assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5);
1640 assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1);
1641 assert!(v.iter().position(|x| *x % 12 == 0).is_none());
1646 let xs = &[1, 2, 2, 1, 5, 9, 0, 2];
1647 assert_eq!(xs.iter().count(|x| *x == 2), 3);
1648 assert_eq!(xs.iter().count(|x| *x == 5), 1);
1649 assert_eq!(xs.iter().count(|x| *x == 95), 0);
1654 let xs = [-3, 0, 1, 5, -10];
1655 assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
1660 let xs = [-3, 0, 1, 5, -10];
1661 assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
1666 let xs = [2, 4, 6, 8, 10, 12, 14, 16];
1667 let mut it = xs.iter();
1670 assert_eq!(it.invert().transform(|&x| x).collect::<~[int]>(), ~[16, 14, 12, 10, 8, 6]);
1674 fn test_double_ended_map() {
1675 let xs = [1, 2, 3, 4, 5, 6];
1676 let mut it = xs.iter().transform(|&x| x * -1);
1677 assert_eq!(it.next(), Some(-1));
1678 assert_eq!(it.next(), Some(-2));
1679 assert_eq!(it.next_back(), Some(-6));
1680 assert_eq!(it.next_back(), Some(-5));
1681 assert_eq!(it.next(), Some(-3));
1682 assert_eq!(it.next_back(), Some(-4));
1683 assert_eq!(it.next(), None);
1687 fn test_double_ended_filter() {
1688 let xs = [1, 2, 3, 4, 5, 6];
1689 let mut it = xs.iter().filter(|&x| *x & 1 == 0);
1690 assert_eq!(it.next_back().unwrap(), &6);
1691 assert_eq!(it.next_back().unwrap(), &4);
1692 assert_eq!(it.next().unwrap(), &2);
1693 assert_eq!(it.next_back(), None);
1697 fn test_double_ended_filter_map() {
1698 let xs = [1, 2, 3, 4, 5, 6];
1699 let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None });
1700 assert_eq!(it.next_back().unwrap(), 12);
1701 assert_eq!(it.next_back().unwrap(), 8);
1702 assert_eq!(it.next().unwrap(), 4);
1703 assert_eq!(it.next_back(), None);
1707 fn test_double_ended_chain() {
1708 let xs = [1, 2, 3, 4, 5];
1709 let ys = ~[7, 9, 11];
1710 let mut it = xs.iter().chain_(ys.iter()).invert();
1711 assert_eq!(it.next().unwrap(), &11)
1712 assert_eq!(it.next().unwrap(), &9)
1713 assert_eq!(it.next_back().unwrap(), &1)
1714 assert_eq!(it.next_back().unwrap(), &2)
1715 assert_eq!(it.next_back().unwrap(), &3)
1716 assert_eq!(it.next_back().unwrap(), &4)
1717 assert_eq!(it.next_back().unwrap(), &5)
1718 assert_eq!(it.next_back().unwrap(), &7)
1719 assert_eq!(it.next_back(), None)