1 // Copyright 2013-2014 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
15 //! This module defines Rust's core iteration trait. The `Iterator` trait has one
16 //! unimplemented method, `next`. All other methods are derived through default
17 //! methods to perform operations such as `zip`, `chain`, `enumerate`, and `fold`.
19 //! The goal of this module is to unify iteration across all containers in Rust.
20 //! An iterator can be considered as a state machine which is used to track which
21 //! element will be yielded next.
23 //! There are various extensions also defined in this module to assist with various
24 //! types of iteration, such as the `DoubleEndedIterator` for iterating in reverse,
25 //! the `FromIterator` trait for creating a container from an iterator, and much
28 //! ## Rust's `for` loop
30 //! The special syntax used by rust's `for` loop is based around the `Iterator`
31 //! trait defined in this module. For loops can be viewed as a syntactical expansion
32 //! into a `loop`, for example, the `for` loop in this example is essentially
33 //! translated to the `loop` below.
36 //! let values = vec![1i, 2, 3];
38 //! // "Syntactical sugar" taking advantage of an iterator
39 //! for &x in values.iter() {
40 //! println!("{}", x);
43 //! // Rough translation of the iteration without a `for` iterator.
44 //! let mut it = values.iter();
48 //! println!("{}", x);
55 //! This `for` loop syntax can be applied to any iterator over any type.
57 pub use self::MinMaxResult::*;
63 use num::{ToPrimitive, Int};
64 use ops::{Add, Deref};
66 use option::Option::{Some, None};
69 #[deprecated = "renamed to Extend"] pub use self::Extend as Extendable;
71 /// Conversion from an `Iterator`
72 #[unstable = "may be replaced by a more general conversion trait"]
73 pub trait FromIterator<A> {
74 /// Build a container with elements from an external iterator.
75 fn from_iter<T: Iterator<A>>(iterator: T) -> Self;
78 /// A type growable from an `Iterator` implementation
79 #[unstable = "just renamed as part of collections reform"]
81 /// Extend a container with the elements yielded by an arbitrary iterator
82 fn extend<T: Iterator<A>>(&mut self, iterator: T);
85 /// An interface for dealing with "external iterators". These types of iterators
86 /// can be resumed at any time as all state is stored internally as opposed to
87 /// being located on the call stack.
89 /// The Iterator protocol states that an iterator yields a (potentially-empty,
90 /// potentially-infinite) sequence of values, and returns `None` to signal that
91 /// it's finished. The Iterator protocol does not define behavior after `None`
92 /// is returned. A concrete Iterator implementation may choose to behave however
93 /// it wishes, either by returning `None` infinitely, or by doing something
96 #[unstable = "just split up for object safety"]
97 pub trait Iterator<A> {
98 /// Advance the iterator and return the next value. Return `None` when the end is reached.
99 fn next(&mut self) -> Option<A>;
101 /// Returns a lower and upper bound on the remaining length of the iterator.
103 /// An upper bound of `None` means either there is no known upper bound, or the upper bound
104 /// does not fit within a `uint`.
106 fn size_hint(&self) -> (uint, Option<uint>) { (0, None) }
109 #[unstable = "new convention for extension traits"]
110 /// An extension trait providing numerous methods applicable to all iterators.
111 pub trait IteratorExt<A>: Iterator<A> {
112 /// Chain this iterator with another, returning a new iterator which will
113 /// finish iterating over the current iterator, and then it will iterate
114 /// over the other specified iterator.
121 /// let mut it = a.iter().chain(b.iter());
122 /// assert_eq!(it.next().unwrap(), &0);
123 /// assert_eq!(it.next().unwrap(), &1);
124 /// assert!(it.next().is_none());
128 fn chain<U: Iterator<A>>(self, other: U) -> Chain<Self, U> {
129 Chain{a: self, b: other, flag: false}
132 /// Creates an iterator which iterates over both this and the specified
133 /// iterators simultaneously, yielding the two elements as pairs. When
134 /// either iterator returns None, all further invocations of next() will
142 /// let mut it = a.iter().zip(b.iter());
143 /// let (x0, x1) = (0i, 1i);
144 /// assert_eq!(it.next().unwrap(), (&x0, &x1));
145 /// assert!(it.next().is_none());
149 fn zip<B, U: Iterator<B>>(self, other: U) -> Zip<Self, U> {
150 Zip{a: self, b: other}
153 /// Creates a new iterator which will apply the specified function to each
154 /// element returned by the first, yielding the mapped element instead.
160 /// let mut it = a.iter().map(|&x| 2 * x);
161 /// assert_eq!(it.next().unwrap(), 2);
162 /// assert_eq!(it.next().unwrap(), 4);
163 /// assert!(it.next().is_none());
166 #[unstable = "waiting for unboxed closures"]
167 fn map<'r, B>(self, f: |A|: 'r -> B) -> Map<'r, A, B, Self> {
168 Map{iter: self, f: f}
171 /// Creates an iterator which applies the predicate to each element returned
172 /// by this iterator. Only elements which have the predicate evaluate to
173 /// `true` will be yielded.
179 /// let mut it = a.iter().filter(|&x| *x > 1);
180 /// assert_eq!(it.next().unwrap(), &2);
181 /// assert!(it.next().is_none());
184 #[unstable = "waiting for unboxed closures"]
185 fn filter<'r>(self, predicate: |&A|: 'r -> bool) -> Filter<'r, A, Self> {
186 Filter{iter: self, predicate: predicate}
189 /// Creates an iterator which both filters and maps elements.
190 /// If the specified function returns None, the element is skipped.
191 /// Otherwise the option is unwrapped and the new value is yielded.
197 /// let mut it = a.iter().filter_map(|&x| if x > 1 {Some(2 * x)} else {None});
198 /// assert_eq!(it.next().unwrap(), 4);
199 /// assert!(it.next().is_none());
202 #[unstable = "waiting for unboxed closures"]
203 fn filter_map<'r, B>(self, f: |A|: 'r -> Option<B>) -> FilterMap<'r, A, B, Self> {
204 FilterMap { iter: self, f: f }
207 /// Creates an iterator which yields a pair of the value returned by this
208 /// iterator plus the current index of iteration.
213 /// let a = [100i, 200];
214 /// let mut it = a.iter().enumerate();
215 /// let (x100, x200) = (100i, 200i);
216 /// assert_eq!(it.next().unwrap(), (0, &x100));
217 /// assert_eq!(it.next().unwrap(), (1, &x200));
218 /// assert!(it.next().is_none());
222 fn enumerate(self) -> Enumerate<Self> {
223 Enumerate{iter: self, count: 0}
227 /// Creates an iterator that has a `.peek()` method
228 /// that returns an optional reference to the next element.
233 /// let xs = [100i, 200, 300];
234 /// let mut it = xs.iter().map(|x| *x).peekable();
235 /// assert_eq!(*it.peek().unwrap(), 100);
236 /// assert_eq!(it.next().unwrap(), 100);
237 /// assert_eq!(it.next().unwrap(), 200);
238 /// assert_eq!(*it.peek().unwrap(), 300);
239 /// assert_eq!(*it.peek().unwrap(), 300);
240 /// assert_eq!(it.next().unwrap(), 300);
241 /// assert!(it.peek().is_none());
242 /// assert!(it.next().is_none());
246 fn peekable(self) -> Peekable<A, Self> {
247 Peekable{iter: self, peeked: None}
250 /// Creates an iterator which invokes the predicate on elements until it
251 /// returns false. Once the predicate returns false, all further elements are
257 /// let a = [1i, 2, 3, 2, 1];
258 /// let mut it = a.iter().skip_while(|&a| *a < 3);
259 /// assert_eq!(it.next().unwrap(), &3);
260 /// assert_eq!(it.next().unwrap(), &2);
261 /// assert_eq!(it.next().unwrap(), &1);
262 /// assert!(it.next().is_none());
265 #[unstable = "waiting for unboxed closures"]
266 fn skip_while<'r>(self, predicate: |&A|: 'r -> bool) -> SkipWhile<'r, A, Self> {
267 SkipWhile{iter: self, flag: false, predicate: predicate}
270 /// Creates an iterator which yields elements so long as the predicate
271 /// returns true. After the predicate returns false for the first time, no
272 /// further elements will be yielded.
277 /// let a = [1i, 2, 3, 2, 1];
278 /// let mut it = a.iter().take_while(|&a| *a < 3);
279 /// assert_eq!(it.next().unwrap(), &1);
280 /// assert_eq!(it.next().unwrap(), &2);
281 /// assert!(it.next().is_none());
284 #[unstable = "waiting for unboxed closures, may want to require peek"]
285 fn take_while<'r>(self, predicate: |&A|: 'r -> bool) -> TakeWhile<'r, A, Self> {
286 TakeWhile{iter: self, flag: false, predicate: predicate}
289 /// Creates an iterator which skips the first `n` elements of this iterator,
290 /// and then it yields all further items.
295 /// let a = [1i, 2, 3, 4, 5];
296 /// let mut it = a.iter().skip(3);
297 /// assert_eq!(it.next().unwrap(), &4);
298 /// assert_eq!(it.next().unwrap(), &5);
299 /// assert!(it.next().is_none());
303 fn skip(self, n: uint) -> Skip<Self> {
304 Skip{iter: self, n: n}
307 /// Creates an iterator which yields the first `n` elements of this
308 /// iterator, and then it will always return None.
313 /// let a = [1i, 2, 3, 4, 5];
314 /// let mut it = a.iter().take(3);
315 /// assert_eq!(it.next().unwrap(), &1);
316 /// assert_eq!(it.next().unwrap(), &2);
317 /// assert_eq!(it.next().unwrap(), &3);
318 /// assert!(it.next().is_none());
322 fn take(self, n: uint) -> Take<Self> {
323 Take{iter: self, n: n}
326 /// Creates a new iterator which behaves in a similar fashion to fold.
327 /// There is a state which is passed between each iteration and can be
328 /// mutated as necessary. The yielded values from the closure are yielded
329 /// from the Scan instance when not None.
334 /// let a = [1i, 2, 3, 4, 5];
335 /// let mut it = a.iter().scan(1, |fac, &x| {
339 /// assert_eq!(it.next().unwrap(), 1);
340 /// assert_eq!(it.next().unwrap(), 2);
341 /// assert_eq!(it.next().unwrap(), 6);
342 /// assert_eq!(it.next().unwrap(), 24);
343 /// assert_eq!(it.next().unwrap(), 120);
344 /// assert!(it.next().is_none());
347 #[unstable = "waiting for unboxed closures"]
348 fn scan<'r, St, B>(self, initial_state: St, f: |&mut St, A|: 'r -> Option<B>)
349 -> Scan<'r, A, B, Self, St> {
350 Scan{iter: self, f: f, state: initial_state}
353 /// Creates an iterator that maps each element to an iterator,
354 /// and yields the elements of the produced iterators
359 /// use std::iter::count;
361 /// let xs = [2u, 3];
362 /// let ys = [0u, 1, 0, 1, 2];
363 /// let mut it = xs.iter().flat_map(|&x| count(0u, 1).take(x));
364 /// // Check that `it` has the same elements as `ys`
367 /// assert_eq!(x, ys[i]);
372 #[unstable = "waiting for unboxed closures"]
373 fn flat_map<'r, B, U: Iterator<B>>(self, f: |A|: 'r -> U)
374 -> FlatMap<'r, A, Self, U> {
375 FlatMap{iter: self, f: f, frontiter: None, backiter: None }
378 /// Creates an iterator that yields `None` forever after the underlying
379 /// iterator yields `None`. Random-access iterator behavior is not
380 /// affected, only single and double-ended iterator behavior.
385 /// fn process<U: Iterator<int>>(it: U) -> int {
386 /// let mut it = it.fuse();
394 /// // did we exhaust the iterator?
395 /// if it.next().is_none() {
400 /// let x = vec![1i,2,3,7,8,9];
401 /// assert_eq!(process(x.into_iter()), 6);
402 /// let x = vec![1i,2,3];
403 /// assert_eq!(process(x.into_iter()), 1006);
407 fn fuse(self) -> Fuse<Self> {
408 Fuse{iter: self, done: false}
411 /// Creates an iterator that calls a function with a reference to each
412 /// element before yielding it. This is often useful for debugging an
413 /// iterator pipeline.
418 /// use std::iter::AdditiveIterator;
420 /// let xs = [1u, 4, 2, 3, 8, 9, 6];
421 /// let sum = xs.iter()
423 /// .inspect(|&x| println!("filtering {}", x))
424 /// .filter(|&x| x % 2 == 0)
425 /// .inspect(|&x| println!("{} made it through", x))
427 /// println!("{}", sum);
430 #[unstable = "waiting for unboxed closures"]
431 fn inspect<'r>(self, f: |&A|: 'r) -> Inspect<'r, A, Self> {
432 Inspect{iter: self, f: f}
435 /// Creates a wrapper around a mutable reference to the iterator.
437 /// This is useful to allow applying iterator adaptors while still
438 /// retaining ownership of the original iterator value.
443 /// let mut xs = range(0u, 10);
444 /// // sum the first five values
445 /// let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b);
446 /// assert!(partial_sum == 10);
447 /// // xs.next() is now `5`
448 /// assert!(xs.next() == Some(5));
451 fn by_ref<'r>(&'r mut self) -> ByRef<'r, Self> {
455 /// Loops through the entire iterator, collecting all of the elements into
456 /// a container implementing `FromIterator`.
461 /// let a = [1i, 2, 3, 4, 5];
462 /// let b: Vec<int> = a.iter().map(|&x| x).collect();
463 /// assert!(a.as_slice() == b.as_slice());
466 #[unstable = "waiting for general conversion traits, just changed to take self by value"]
467 fn collect<B: FromIterator<A>>(self) -> B {
468 FromIterator::from_iter(self)
471 /// Loops through `n` iterations, returning the `n`th element of the
477 /// let a = [1i, 2, 3, 4, 5];
478 /// let mut it = a.iter();
479 /// assert!(it.nth(2).unwrap() == &3);
480 /// assert!(it.nth(2) == None);
484 fn nth(&mut self, mut n: uint) -> Option<A> {
486 if n == 0 { return Some(x) }
492 /// Loops through the entire iterator, returning the last element of the
498 /// let a = [1i, 2, 3, 4, 5];
499 /// assert!(a.iter().last().unwrap() == &5);
502 #[unstable = "just changed to take self by value"]
503 fn last(mut self) -> Option<A> {
505 for x in self { last = Some(x); }
509 /// Performs a fold operation over the entire iterator, returning the
510 /// eventual state at the end of the iteration.
515 /// let a = [1i, 2, 3, 4, 5];
516 /// assert!(a.iter().fold(0, |a, &b| a + b) == 15);
519 #[unstable = "waiting for unboxed closures, just changed to take self by value"]
520 fn fold<B>(mut self, init: B, f: |B, A| -> B) -> B {
521 let mut accum = init;
528 /// Counts the number of elements in this iterator.
533 /// let a = [1i, 2, 3, 4, 5];
534 /// let mut it = a.iter();
535 /// assert!(it.count() == 5);
538 #[unstable = "just changed to take self by value"]
539 fn count(self) -> uint {
540 self.fold(0, |cnt, _x| cnt + 1)
543 /// Tests whether the predicate holds true for all elements in the iterator.
548 /// let a = [1i, 2, 3, 4, 5];
549 /// assert!(a.iter().all(|x| *x > 0));
550 /// assert!(!a.iter().all(|x| *x > 2));
553 #[unstable = "waiting for unboxed closures, just changed to take self by value"]
554 fn all(mut self, f: |A| -> bool) -> bool {
555 for x in self { if !f(x) { return false; } }
559 /// Tests whether any element of an iterator satisfies the specified
565 /// let a = [1i, 2, 3, 4, 5];
566 /// let mut it = a.iter();
567 /// assert!(it.any(|x| *x == 3));
568 /// assert!(!it.any(|x| *x == 3));
571 #[unstable = "waiting for unboxed closures"]
572 fn any(&mut self, f: |A| -> bool) -> bool {
573 for x in *self { if f(x) { return true; } }
577 /// Returns the first element satisfying the specified predicate.
579 /// Does not consume the iterator past the first found element.
581 #[unstable = "waiting for unboxed closures"]
582 fn find(&mut self, predicate: |&A| -> bool) -> Option<A> {
584 if predicate(&x) { return Some(x) }
589 /// Return the index of the first element satisfying the specified predicate
591 #[unstable = "waiting for unboxed closures"]
592 fn position(&mut self, predicate: |A| -> bool) -> Option<uint> {
603 /// Return the element that gives the maximum value from the
604 /// specified function.
609 /// use core::num::SignedInt;
611 /// let xs = [-3i, 0, 1, 5, -10];
612 /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10);
615 #[unstable = "waiting for unboxed closures, just changed to take self by value"]
616 fn max_by<B: Ord>(self, f: |&A| -> B) -> Option<A> {
617 self.fold(None, |max: Option<(A, B)>, x| {
620 None => Some((x, x_val)),
621 Some((y, y_val)) => if x_val > y_val {
630 /// Return the element that gives the minimum value from the
631 /// specified function.
636 /// use core::num::SignedInt;
638 /// let xs = [-3i, 0, 1, 5, -10];
639 /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0);
642 #[unstable = "waiting for unboxed closures, just changed to take self by value"]
643 fn min_by<B: Ord>(self, f: |&A| -> B) -> Option<A> {
644 self.fold(None, |min: Option<(A, B)>, x| {
647 None => Some((x, x_val)),
648 Some((y, y_val)) => if x_val < y_val {
658 #[unstable = "trait is unstable"]
659 impl<A, I> IteratorExt<A> for I where I: Iterator<A> {}
661 /// A range iterator able to yield elements from both ends
663 /// A `DoubleEndedIterator` can be thought of as a deque in that `next()` and `next_back()` exhaust
664 /// elements from the *same* range, and do not work independently of each other.
665 #[unstable = "recently split into two traits"]
666 pub trait DoubleEndedIterator<A>: Iterator<A> {
667 /// Yield an element from the end of the range, returning `None` if the range is empty.
668 fn next_back(&mut self) -> Option<A>;
671 /// Extension methods for double-ended iterators.
672 #[unstable = "new extension trait convention"]
673 pub trait DoubleEndedIteratorExt<A>: DoubleEndedIterator<A> {
674 /// Change the direction of the iterator
676 /// The flipped iterator swaps the ends on an iterator that can already
677 /// be iterated from the front and from the back.
680 /// If the iterator also implements RandomAccessIterator, the flipped
681 /// iterator is also random access, with the indices starting at the back
682 /// of the original iterator.
684 /// Note: Random access with flipped indices still only applies to the first
685 /// `uint::MAX` elements of the original iterator.
688 fn rev(self) -> Rev<Self> {
693 #[unstable = "trait is unstable"]
694 impl<A, I> DoubleEndedIteratorExt<A> for I where I: DoubleEndedIterator<A> {}
696 /// A double-ended iterator yielding mutable references
697 #[experimental = "not widely used"]
698 pub trait MutableDoubleEndedIterator {
699 // FIXME: #5898: should be called `reverse`
700 /// Use an iterator to reverse a container in-place
701 fn reverse_(&mut self);
704 #[experimental = "trait is experimental"]
705 impl<'a, A:'a, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T {
706 // FIXME: #5898: should be called `reverse`
707 /// Use an iterator to reverse a container in-place
708 fn reverse_(&mut self) {
710 match (self.next(), self.next_back()) {
711 (Some(x), Some(y)) => mem::swap(x, y),
719 /// An object implementing random access indexing by `uint`
721 /// A `RandomAccessIterator` should be either infinite or a `DoubleEndedIterator`.
722 /// Calling `next()` or `next_back()` on a `RandomAccessIterator`
723 /// reduces the indexable range accordingly. That is, `it.idx(1)` will become `it.idx(0)`
724 /// after `it.next()` is called.
725 #[experimental = "not widely used, may be better decomposed into Index and ExactSizeIterator"]
726 pub trait RandomAccessIterator<A>: Iterator<A> {
727 /// Return the number of indexable elements. At most `std::uint::MAX`
728 /// elements are indexable, even if the iterator represents a longer range.
729 fn indexable(&self) -> uint;
731 /// Return an element at an index, or `None` if the index is out of bounds
732 fn idx(&mut self, index: uint) -> Option<A>;
735 /// An iterator that knows its exact length
737 /// This trait is a helper for iterators like the vector iterator, so that
738 /// it can support double-ended enumeration.
740 /// `Iterator::size_hint` *must* return the exact size of the iterator.
741 /// Note that the size must fit in `uint`.
742 #[unstable = "could move DoubleEndedIterator bound onto rposition with method-level where clauses"]
743 pub trait ExactSizeIterator<A> : DoubleEndedIterator<A> {
744 /// Return the index of the last element satisfying the specified predicate
746 /// If no element matches, None is returned.
748 fn rposition(&mut self, predicate: |A| -> bool) -> Option<uint> {
749 let len = self.len();
750 for i in range(0, len).rev() {
751 if predicate(self.next_back().expect("rposition: incorrect ExactSizeIterator")) {
759 /// Return the exact length of the iterator.
760 fn len(&self) -> uint {
761 let (lower, upper) = self.size_hint();
762 // Note: This assertion is overly defensive, but it checks the invariant
763 // guaranteed by the trait. If this trait were rust-internal,
764 // we could use debug_assert!; assert_eq! will check all Rust user
765 // implementations too.
766 assert_eq!(upper, Some(lower));
771 // All adaptors that preserve the size of the wrapped iterator are fine
772 // Adaptors that may overflow in `size_hint` are not, i.e. `Chain`.
773 #[unstable = "trait is unstable"]
774 impl<A, T: ExactSizeIterator<A>> ExactSizeIterator<(uint, A)> for Enumerate<T> {}
775 #[unstable = "trait is unstable"]
776 impl<'a, A, T: ExactSizeIterator<A>> ExactSizeIterator<A> for Inspect<'a, A, T> {}
777 #[unstable = "trait is unstable"]
778 impl<A, T: ExactSizeIterator<A>> ExactSizeIterator<A> for Rev<T> {}
779 #[unstable = "trait is unstable"]
780 impl<'a, A, B, T: ExactSizeIterator<A>> ExactSizeIterator<B> for Map<'a, A, B, T> {}
781 #[unstable = "trait is unstable"]
782 impl<A, B, T, U> ExactSizeIterator<(A, B)> for Zip<T, U>
783 where T: ExactSizeIterator<A>, U: ExactSizeIterator<B> {}
785 /// An double-ended iterator with the direction inverted
787 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
793 #[unstable = "trait is unstable"]
794 impl<A, T: DoubleEndedIterator<A>> Iterator<A> for Rev<T> {
796 fn next(&mut self) -> Option<A> { self.iter.next_back() }
798 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
801 #[unstable = "trait is unstable"]
802 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Rev<T> {
804 fn next_back(&mut self) -> Option<A> { self.iter.next() }
807 #[experimental = "trait is experimental"]
808 impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
811 fn indexable(&self) -> uint { self.iter.indexable() }
813 fn idx(&mut self, index: uint) -> Option<A> {
814 let amt = self.indexable();
815 self.iter.idx(amt - index - 1)
819 /// A mutable reference to an iterator
820 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
822 pub struct ByRef<'a, T:'a> {
826 #[unstable = "trait is unstable"]
827 impl<'a, A, T: Iterator<A>+'a> Iterator<A> for ByRef<'a, T> {
829 fn next(&mut self) -> Option<A> { self.iter.next() }
831 fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
834 #[unstable = "trait is unstable"]
835 impl<'a, A, T: DoubleEndedIterator<A>+'a> DoubleEndedIterator<A> for ByRef<'a, T> {
837 fn next_back(&mut self) -> Option<A> { self.iter.next_back() }
840 /// A trait for iterators over elements which can be added together
841 #[experimental = "needs to be re-evaluated as part of numerics reform"]
842 pub trait AdditiveIterator<A> {
843 /// Iterates over the entire iterator, summing up all the elements
848 /// use std::iter::AdditiveIterator;
850 /// let a = [1i, 2, 3, 4, 5];
851 /// let mut it = a.iter().map(|&x| x);
852 /// assert!(it.sum() == 15);
857 macro_rules! impl_additive {
858 ($A:ty, $init:expr) => {
859 #[experimental = "trait is experimental"]
860 impl<T: Iterator<$A>> AdditiveIterator<$A> for T {
863 self.fold($init, |acc, x| acc + x)
868 impl_additive!(i8, 0)
869 impl_additive!(i16, 0)
870 impl_additive!(i32, 0)
871 impl_additive!(i64, 0)
872 impl_additive!(int, 0)
873 impl_additive!(u8, 0)
874 impl_additive!(u16, 0)
875 impl_additive!(u32, 0)
876 impl_additive!(u64, 0)
877 impl_additive!(uint, 0)
878 impl_additive!(f32, 0.0)
879 impl_additive!(f64, 0.0)
881 /// A trait for iterators over elements which can be multiplied together.
882 #[experimental = "needs to be re-evaluated as part of numerics reform"]
883 pub trait MultiplicativeIterator<A> {
884 /// Iterates over the entire iterator, multiplying all the elements
889 /// use std::iter::{count, MultiplicativeIterator};
891 /// fn factorial(n: uint) -> uint {
892 /// count(1u, 1).take_while(|&i| i <= n).product()
894 /// assert!(factorial(0) == 1);
895 /// assert!(factorial(1) == 1);
896 /// assert!(factorial(5) == 120);
898 fn product(self) -> A;
901 macro_rules! impl_multiplicative {
902 ($A:ty, $init:expr) => {
903 #[experimental = "trait is experimental"]
904 impl<T: Iterator<$A>> MultiplicativeIterator<$A> for T {
906 fn product(self) -> $A {
907 self.fold($init, |acc, x| acc * x)
912 impl_multiplicative!(i8, 1)
913 impl_multiplicative!(i16, 1)
914 impl_multiplicative!(i32, 1)
915 impl_multiplicative!(i64, 1)
916 impl_multiplicative!(int, 1)
917 impl_multiplicative!(u8, 1)
918 impl_multiplicative!(u16, 1)
919 impl_multiplicative!(u32, 1)
920 impl_multiplicative!(u64, 1)
921 impl_multiplicative!(uint, 1)
922 impl_multiplicative!(f32, 1.0)
923 impl_multiplicative!(f64, 1.0)
925 /// A trait for iterators over elements which can be compared to one another.
926 #[unstable = "recently renamed for new extension trait conventions"]
927 pub trait IteratorOrdExt<A> {
928 /// Consumes the entire iterator to return the maximum element.
933 /// let a = [1i, 2, 3, 4, 5];
934 /// assert!(a.iter().max().unwrap() == &5);
936 fn max(self) -> Option<A>;
938 /// Consumes the entire iterator to return the minimum element.
943 /// let a = [1i, 2, 3, 4, 5];
944 /// assert!(a.iter().min().unwrap() == &1);
946 fn min(self) -> Option<A>;
948 /// `min_max` finds the minimum and maximum elements in the iterator.
950 /// The return type `MinMaxResult` is an enum of three variants:
952 /// - `NoElements` if the iterator is empty.
953 /// - `OneElement(x)` if the iterator has exactly one element.
954 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
955 /// values are equal if and only if there is more than one
956 /// element in the iterator and all elements are equal.
958 /// On an iterator of length `n`, `min_max` does `1.5 * n` comparisons,
959 /// and so is faster than calling `min` and `max` separately which does `2 * n` comparisons.
964 /// use std::iter::{NoElements, OneElement, MinMax};
966 /// let v: [int, ..0] = [];
967 /// assert_eq!(v.iter().min_max(), NoElements);
970 /// assert!(v.iter().min_max() == OneElement(&1));
972 /// let v = [1i, 2, 3, 4, 5];
973 /// assert!(v.iter().min_max() == MinMax(&1, &5));
975 /// let v = [1i, 2, 3, 4, 5, 6];
976 /// assert!(v.iter().min_max() == MinMax(&1, &6));
978 /// let v = [1i, 1, 1, 1];
979 /// assert!(v.iter().min_max() == MinMax(&1, &1));
981 fn min_max(self) -> MinMaxResult<A>;
984 #[unstable = "trait is unstable"]
985 impl<A: Ord, T: Iterator<A>> IteratorOrdExt<A> for T {
987 fn max(self) -> Option<A> {
988 self.fold(None, |max, x| {
991 Some(y) => Some(cmp::max(x, y))
997 fn min(self) -> Option<A> {
998 self.fold(None, |min, x| {
1001 Some(y) => Some(cmp::min(x, y))
1006 fn min_max(mut self) -> MinMaxResult<A> {
1007 let (mut min, mut max) = match self.next() {
1008 None => return NoElements,
1011 None => return OneElement(x),
1012 Some(y) => if x < y {(x, y)} else {(y,x)}
1018 // `first` and `second` are the two next elements we want to look at.
1019 // We first compare `first` and `second` (#1). The smaller one is then compared to
1020 // current minimum (#2). The larger one is compared to current maximum (#3). This
1021 // way we do 3 comparisons for 2 elements.
1022 let first = match self.next() {
1026 let second = match self.next() {
1030 } else if first > max {
1038 if first < min {min = first;}
1039 if max < second {max = second;}
1041 if second < min {min = second;}
1042 if max < first {max = first;}
1050 /// `MinMaxResult` is an enum returned by `min_max`. See `IteratorOrdExt::min_max` for more detail.
1051 #[deriving(Clone, PartialEq, Show)]
1052 #[unstable = "waiting on namespaced enum conventions"]
1053 pub enum MinMaxResult<T> {
1057 /// Iterator with one element, so the minimum and maximum are the same
1060 /// More than one element in the iterator, the first element is not larger than the second
1065 impl<T: Clone> MinMaxResult<T> {
1066 /// `into_option` creates an `Option` of type `(T,T)`. The returned `Option` has variant
1067 /// `None` if and only if the `MinMaxResult` has variant `NoElements`. Otherwise variant
1068 /// `Some(x,y)` is returned where `x <= y`. If `MinMaxResult` has variant `OneElement(x)`,
1069 /// performing this operation will make one clone of `x`.
1074 /// use std::iter::{NoElements, OneElement, MinMax, MinMaxResult};
1076 /// let r: MinMaxResult<int> = NoElements;
1077 /// assert_eq!(r.into_option(), None)
1079 /// let r = OneElement(1i);
1080 /// assert_eq!(r.into_option(), Some((1,1)));
1082 /// let r = MinMax(1i,2i);
1083 /// assert_eq!(r.into_option(), Some((1,2)));
1085 pub fn into_option(self) -> Option<(T,T)> {
1088 OneElement(x) => Some((x.clone(), x)),
1089 MinMax(x, y) => Some((x, y))
1094 /// A trait for iterators that contain cloneable elements
1095 #[unstable = "recently renamed for extension trait conventions"]
1096 pub trait IteratorCloneExt<A> {
1097 /// Creates an iterator that clones the elements it yields. Useful for converting an
1098 /// Iterator<&T> to an Iterator<T>.
1099 fn cloned(self) -> Cloned<Self>;
1102 #[unstable = "trait is unstable"]
1103 impl<A: Clone, D: Deref<A>, I: Iterator<D>> IteratorCloneExt<A> for I {
1104 fn cloned(self) -> Cloned<I> {
1109 /// An iterator that clones the elements of an underlying iterator
1110 pub struct Cloned<I> {
1114 impl<A: Clone, D: Deref<A>, I: Iterator<D>> Iterator<A> for Cloned<I> {
1115 fn next(&mut self) -> Option<A> {
1116 self.it.next().cloned()
1119 fn size_hint(&self) -> (uint, Option<uint>) {
1124 impl<A: Clone, D: Deref<A>, I: DoubleEndedIterator<D>>
1125 DoubleEndedIterator<A> for Cloned<I> {
1126 fn next_back(&mut self) -> Option<A> {
1127 self.it.next_back().cloned()
1131 #[unstable = "trait is unstable"]
1132 impl<A: Clone, D: Deref<A>, I: ExactSizeIterator<D>> ExactSizeIterator<A> for Cloned<I> {}
1134 #[unstable = "recently renamed for extension trait conventions"]
1135 /// An extension trait for cloneable iterators.
1136 pub trait CloneIteratorExt {
1137 /// Repeats an iterator endlessly
1142 /// use std::iter::{CloneIteratorExt, count};
1144 /// let a = count(1i,1i).take(1);
1145 /// let mut cy = a.cycle();
1146 /// assert_eq!(cy.next(), Some(1));
1147 /// assert_eq!(cy.next(), Some(1));
1150 fn cycle(self) -> Cycle<Self>;
1153 impl<A, I> CloneIteratorExt for I where I: Iterator<A> + Clone {
1155 fn cycle(self) -> Cycle<I> {
1156 Cycle{orig: self.clone(), iter: self}
1160 /// An iterator that repeats endlessly
1162 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1164 pub struct Cycle<T> {
1169 #[unstable = "trait is unstable"]
1170 impl<A, T: Clone + Iterator<A>> Iterator<A> for Cycle<T> {
1172 fn next(&mut self) -> Option<A> {
1173 match self.iter.next() {
1174 None => { self.iter = self.orig.clone(); self.iter.next() }
1180 fn size_hint(&self) -> (uint, Option<uint>) {
1181 // the cycle iterator is either empty or infinite
1182 match self.orig.size_hint() {
1183 sz @ (0, Some(0)) => sz,
1184 (0, _) => (0, None),
1185 _ => (uint::MAX, None)
1190 #[experimental = "trait is experimental"]
1191 impl<A, T: Clone + RandomAccessIterator<A>> RandomAccessIterator<A> for Cycle<T> {
1193 fn indexable(&self) -> uint {
1194 if self.orig.indexable() > 0 {
1202 fn idx(&mut self, index: uint) -> Option<A> {
1203 let liter = self.iter.indexable();
1204 let lorig = self.orig.indexable();
1207 } else if index < liter {
1208 self.iter.idx(index)
1210 self.orig.idx((index - liter) % lorig)
1215 /// An iterator which strings two iterators together
1217 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1219 pub struct Chain<T, U> {
1225 #[unstable = "trait is unstable"]
1226 impl<A, T: Iterator<A>, U: Iterator<A>> Iterator<A> for Chain<T, U> {
1228 fn next(&mut self) -> Option<A> {
1232 match self.a.next() {
1233 Some(x) => return Some(x),
1242 fn size_hint(&self) -> (uint, Option<uint>) {
1243 let (a_lower, a_upper) = self.a.size_hint();
1244 let (b_lower, b_upper) = self.b.size_hint();
1246 let lower = a_lower.saturating_add(b_lower);
1248 let upper = match (a_upper, b_upper) {
1249 (Some(x), Some(y)) => x.checked_add(y),
1257 #[unstable = "trait is unstable"]
1258 impl<A, T: DoubleEndedIterator<A>, U: DoubleEndedIterator<A>> DoubleEndedIterator<A>
1261 fn next_back(&mut self) -> Option<A> {
1262 match self.b.next_back() {
1264 None => self.a.next_back()
1269 #[experimental = "trait is experimental"]
1270 impl<A, T: RandomAccessIterator<A>, U: RandomAccessIterator<A>> RandomAccessIterator<A>
1273 fn indexable(&self) -> uint {
1274 let (a, b) = (self.a.indexable(), self.b.indexable());
1279 fn idx(&mut self, index: uint) -> Option<A> {
1280 let len = self.a.indexable();
1284 self.b.idx(index - len)
1289 /// An iterator which iterates two other iterators simultaneously
1291 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1293 pub struct Zip<T, U> {
1298 #[unstable = "trait is unstable"]
1299 impl<A, B, T: Iterator<A>, U: Iterator<B>> Iterator<(A, B)> for Zip<T, U> {
1301 fn next(&mut self) -> Option<(A, B)> {
1302 match self.a.next() {
1304 Some(x) => match self.b.next() {
1306 Some(y) => Some((x, y))
1312 fn size_hint(&self) -> (uint, Option<uint>) {
1313 let (a_lower, a_upper) = self.a.size_hint();
1314 let (b_lower, b_upper) = self.b.size_hint();
1316 let lower = cmp::min(a_lower, b_lower);
1318 let upper = match (a_upper, b_upper) {
1319 (Some(x), Some(y)) => Some(cmp::min(x,y)),
1320 (Some(x), None) => Some(x),
1321 (None, Some(y)) => Some(y),
1322 (None, None) => None
1329 #[unstable = "trait is unstable"]
1330 impl<A, B, T: ExactSizeIterator<A>, U: ExactSizeIterator<B>> DoubleEndedIterator<(A, B)>
1333 fn next_back(&mut self) -> Option<(A, B)> {
1334 let a_sz = self.a.len();
1335 let b_sz = self.b.len();
1337 // Adjust a, b to equal length
1339 for _ in range(0, a_sz - b_sz) { self.a.next_back(); }
1341 for _ in range(0, b_sz - a_sz) { self.b.next_back(); }
1344 match (self.a.next_back(), self.b.next_back()) {
1345 (Some(x), Some(y)) => Some((x, y)),
1346 (None, None) => None,
1347 _ => unreachable!(),
1352 #[experimental = "trait is experimental"]
1353 impl<A, B, T: RandomAccessIterator<A>, U: RandomAccessIterator<B>>
1354 RandomAccessIterator<(A, B)> for Zip<T, U> {
1356 fn indexable(&self) -> uint {
1357 cmp::min(self.a.indexable(), self.b.indexable())
1361 fn idx(&mut self, index: uint) -> Option<(A, B)> {
1362 match self.a.idx(index) {
1364 Some(x) => match self.b.idx(index) {
1366 Some(y) => Some((x, y))
1372 /// An iterator which maps the values of `iter` with `f`
1373 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1375 pub struct Map<'a, A, B, T> {
1380 impl<'a, A, B, T> Map<'a, A, B, T> {
1382 fn do_map(&mut self, elt: Option<A>) -> Option<B> {
1384 Some(a) => Some((self.f)(a)),
1390 #[unstable = "trait is unstable"]
1391 impl<'a, A, B, T: Iterator<A>> Iterator<B> for Map<'a, A, B, T> {
1393 fn next(&mut self) -> Option<B> {
1394 let next = self.iter.next();
1399 fn size_hint(&self) -> (uint, Option<uint>) {
1400 self.iter.size_hint()
1404 #[unstable = "trait is unstable"]
1405 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B> for Map<'a, A, B, T> {
1407 fn next_back(&mut self) -> Option<B> {
1408 let next = self.iter.next_back();
1413 #[experimental = "trait is experimental"]
1414 impl<'a, A, B, T: RandomAccessIterator<A>> RandomAccessIterator<B> for Map<'a, A, B, T> {
1416 fn indexable(&self) -> uint {
1417 self.iter.indexable()
1421 fn idx(&mut self, index: uint) -> Option<B> {
1422 let elt = self.iter.idx(index);
1427 /// An iterator which filters the elements of `iter` with `predicate`
1428 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1430 pub struct Filter<'a, A, T> {
1432 predicate: |&A|: 'a -> bool
1435 #[unstable = "trait is unstable"]
1436 impl<'a, A, T: Iterator<A>> Iterator<A> for Filter<'a, A, T> {
1438 fn next(&mut self) -> Option<A> {
1439 for x in self.iter {
1440 if (self.predicate)(&x) {
1450 fn size_hint(&self) -> (uint, Option<uint>) {
1451 let (_, upper) = self.iter.size_hint();
1452 (0, upper) // can't know a lower bound, due to the predicate
1456 #[unstable = "trait is unstable"]
1457 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Filter<'a, A, T> {
1459 fn next_back(&mut self) -> Option<A> {
1460 for x in self.iter.by_ref().rev() {
1461 if (self.predicate)(&x) {
1469 /// An iterator which uses `f` to both filter and map elements from `iter`
1470 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1472 pub struct FilterMap<'a, A, B, T> {
1474 f: |A|: 'a -> Option<B>
1477 #[unstable = "trait is unstable"]
1478 impl<'a, A, B, T: Iterator<A>> Iterator<B> for FilterMap<'a, A, B, T> {
1480 fn next(&mut self) -> Option<B> {
1481 for x in self.iter {
1483 Some(y) => return Some(y),
1491 fn size_hint(&self) -> (uint, Option<uint>) {
1492 let (_, upper) = self.iter.size_hint();
1493 (0, upper) // can't know a lower bound, due to the predicate
1497 #[unstable = "trait is unstable"]
1498 impl<'a, A, B, T: DoubleEndedIterator<A>> DoubleEndedIterator<B>
1499 for FilterMap<'a, A, B, T> {
1501 fn next_back(&mut self) -> Option<B> {
1502 for x in self.iter.by_ref().rev() {
1504 Some(y) => return Some(y),
1512 /// An iterator which yields the current count and the element during iteration
1514 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1516 pub struct Enumerate<T> {
1521 #[unstable = "trait is unstable"]
1522 impl<A, T: Iterator<A>> Iterator<(uint, A)> for Enumerate<T> {
1524 fn next(&mut self) -> Option<(uint, A)> {
1525 match self.iter.next() {
1527 let ret = Some((self.count, a));
1536 fn size_hint(&self) -> (uint, Option<uint>) {
1537 self.iter.size_hint()
1541 #[unstable = "trait is unstable"]
1542 impl<A, T: ExactSizeIterator<A>> DoubleEndedIterator<(uint, A)> for Enumerate<T> {
1544 fn next_back(&mut self) -> Option<(uint, A)> {
1545 match self.iter.next_back() {
1547 let len = self.iter.len();
1548 Some((self.count + len, a))
1555 #[experimental = "trait is experimental"]
1556 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<(uint, A)> for Enumerate<T> {
1558 fn indexable(&self) -> uint {
1559 self.iter.indexable()
1563 fn idx(&mut self, index: uint) -> Option<(uint, A)> {
1564 match self.iter.idx(index) {
1565 Some(a) => Some((self.count + index, a)),
1571 /// An iterator with a `peek()` that returns an optional reference to the next element.
1572 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1574 pub struct Peekable<A, T> {
1579 #[unstable = "trait is unstable"]
1580 impl<A, T: Iterator<A>> Iterator<A> for Peekable<A, T> {
1582 fn next(&mut self) -> Option<A> {
1583 if self.peeked.is_some() { self.peeked.take() }
1584 else { self.iter.next() }
1588 fn size_hint(&self) -> (uint, Option<uint>) {
1589 let (lo, hi) = self.iter.size_hint();
1590 if self.peeked.is_some() {
1591 let lo = lo.saturating_add(1);
1593 Some(x) => x.checked_add(1),
1604 impl<'a, A, T: Iterator<A>> Peekable<A, T> {
1605 /// Return a reference to the next element of the iterator with out advancing it,
1606 /// or None if the iterator is exhausted.
1608 pub fn peek(&'a mut self) -> Option<&'a A> {
1609 if self.peeked.is_none() {
1610 self.peeked = self.iter.next();
1613 Some(ref value) => Some(value),
1618 /// Check whether peekable iterator is empty or not.
1620 pub fn is_empty(&mut self) -> bool {
1621 self.peek().is_none()
1625 /// An iterator which rejects elements while `predicate` is true
1626 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1628 pub struct SkipWhile<'a, A, T> {
1631 predicate: |&A|: 'a -> bool
1634 #[unstable = "trait is unstable"]
1635 impl<'a, A, T: Iterator<A>> Iterator<A> for SkipWhile<'a, A, T> {
1637 fn next(&mut self) -> Option<A> {
1638 for x in self.iter {
1639 if self.flag || !(self.predicate)(&x) {
1648 fn size_hint(&self) -> (uint, Option<uint>) {
1649 let (_, upper) = self.iter.size_hint();
1650 (0, upper) // can't know a lower bound, due to the predicate
1654 /// An iterator which only accepts elements while `predicate` is true
1655 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1657 pub struct TakeWhile<'a, A, T> {
1660 predicate: |&A|: 'a -> bool
1663 #[unstable = "trait is unstable"]
1664 impl<'a, A, T: Iterator<A>> Iterator<A> for TakeWhile<'a, A, T> {
1666 fn next(&mut self) -> Option<A> {
1670 match self.iter.next() {
1672 if (self.predicate)(&x) {
1685 fn size_hint(&self) -> (uint, Option<uint>) {
1686 let (_, upper) = self.iter.size_hint();
1687 (0, upper) // can't know a lower bound, due to the predicate
1691 /// An iterator which skips over `n` elements of `iter`.
1693 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1695 pub struct Skip<T> {
1700 #[unstable = "trait is unstable"]
1701 impl<A, T: Iterator<A>> Iterator<A> for Skip<T> {
1703 fn next(&mut self) -> Option<A> {
1704 let mut next = self.iter.next();
1713 next = self.iter.next();
1728 fn size_hint(&self) -> (uint, Option<uint>) {
1729 let (lower, upper) = self.iter.size_hint();
1731 let lower = lower.saturating_sub(self.n);
1733 let upper = match upper {
1734 Some(x) => Some(x.saturating_sub(self.n)),
1742 #[experimental = "trait is experimental"]
1743 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Skip<T> {
1745 fn indexable(&self) -> uint {
1746 self.iter.indexable().saturating_sub(self.n)
1750 fn idx(&mut self, index: uint) -> Option<A> {
1751 if index >= self.indexable() {
1754 self.iter.idx(index + self.n)
1759 /// An iterator which only iterates over the first `n` iterations of `iter`.
1761 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1763 pub struct Take<T> {
1768 #[unstable = "trait is unstable"]
1769 impl<A, T: Iterator<A>> Iterator<A> for Take<T> {
1771 fn next(&mut self) -> Option<A> {
1781 fn size_hint(&self) -> (uint, Option<uint>) {
1782 let (lower, upper) = self.iter.size_hint();
1784 let lower = cmp::min(lower, self.n);
1786 let upper = match upper {
1787 Some(x) if x < self.n => Some(x),
1795 #[experimental = "trait is experimental"]
1796 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Take<T> {
1798 fn indexable(&self) -> uint {
1799 cmp::min(self.iter.indexable(), self.n)
1803 fn idx(&mut self, index: uint) -> Option<A> {
1804 if index >= self.n {
1807 self.iter.idx(index)
1813 /// An iterator to maintain state while iterating another iterator
1814 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1815 #[unstable = "waiting for unboxed closures"]
1816 pub struct Scan<'a, A, B, T, St> {
1818 f: |&mut St, A|: 'a -> Option<B>,
1820 /// The current internal state to be passed to the closure next.
1824 #[unstable = "trait is unstable"]
1825 impl<'a, A, B, T: Iterator<A>, St> Iterator<B> for Scan<'a, A, B, T, St> {
1827 fn next(&mut self) -> Option<B> {
1828 self.iter.next().and_then(|a| (self.f)(&mut self.state, a))
1832 fn size_hint(&self) -> (uint, Option<uint>) {
1833 let (_, upper) = self.iter.size_hint();
1834 (0, upper) // can't know a lower bound, due to the scan function
1838 /// An iterator that maps each element to an iterator,
1839 /// and yields the elements of the produced iterators
1841 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1842 #[unstable = "waiting for unboxed closures"]
1843 pub struct FlatMap<'a, A, T, U> {
1846 frontiter: Option<U>,
1847 backiter: Option<U>,
1850 #[unstable = "trait is unstable"]
1851 impl<'a, A, T: Iterator<A>, B, U: Iterator<B>> Iterator<B> for FlatMap<'a, A, T, U> {
1853 fn next(&mut self) -> Option<B> {
1855 for inner in self.frontiter.iter_mut() {
1860 match self.iter.next().map(|x| (self.f)(x)) {
1861 None => return self.backiter.as_mut().and_then(|it| it.next()),
1862 next => self.frontiter = next,
1868 fn size_hint(&self) -> (uint, Option<uint>) {
1869 let (flo, fhi) = self.frontiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1870 let (blo, bhi) = self.backiter.as_ref().map_or((0, Some(0)), |it| it.size_hint());
1871 let lo = flo.saturating_add(blo);
1872 match (self.iter.size_hint(), fhi, bhi) {
1873 ((0, Some(0)), Some(a), Some(b)) => (lo, a.checked_add(b)),
1879 #[unstable = "trait is unstable"]
1881 A, T: DoubleEndedIterator<A>,
1882 B, U: DoubleEndedIterator<B>> DoubleEndedIterator<B>
1883 for FlatMap<'a, A, T, U> {
1885 fn next_back(&mut self) -> Option<B> {
1887 for inner in self.backiter.iter_mut() {
1888 match inner.next_back() {
1893 match self.iter.next_back().map(|x| (self.f)(x)) {
1894 None => return self.frontiter.as_mut().and_then(|it| it.next_back()),
1895 next => self.backiter = next,
1901 /// An iterator that yields `None` forever after the underlying iterator
1902 /// yields `None` once.
1904 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1906 pub struct Fuse<T> {
1911 #[unstable = "trait is unstable"]
1912 impl<A, T: Iterator<A>> Iterator<A> for Fuse<T> {
1914 fn next(&mut self) -> Option<A> {
1918 match self.iter.next() {
1929 fn size_hint(&self) -> (uint, Option<uint>) {
1933 self.iter.size_hint()
1938 #[unstable = "trait is unstable"]
1939 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Fuse<T> {
1941 fn next_back(&mut self) -> Option<A> {
1945 match self.iter.next_back() {
1956 // Allow RandomAccessIterators to be fused without affecting random-access behavior
1957 #[experimental = "trait is experimental"]
1958 impl<A, T: RandomAccessIterator<A>> RandomAccessIterator<A> for Fuse<T> {
1960 fn indexable(&self) -> uint {
1961 self.iter.indexable()
1965 fn idx(&mut self, index: uint) -> Option<A> {
1966 self.iter.idx(index)
1970 #[experimental = "seems marginal"]
1972 /// Resets the fuse such that the next call to .next() or .next_back() will
1973 /// call the underlying iterator again even if it previously returned None.
1975 pub fn reset_fuse(&mut self) {
1980 /// An iterator that calls a function with a reference to each
1981 /// element before yielding it.
1982 #[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
1983 #[unstable = "waiting for unboxed closures"]
1984 pub struct Inspect<'a, A, T> {
1989 impl<'a, A, T> Inspect<'a, A, T> {
1991 fn do_inspect(&mut self, elt: Option<A>) -> Option<A> {
1993 Some(ref a) => (self.f)(a),
2001 #[unstable = "trait is unstable"]
2002 impl<'a, A, T: Iterator<A>> Iterator<A> for Inspect<'a, A, T> {
2004 fn next(&mut self) -> Option<A> {
2005 let next = self.iter.next();
2006 self.do_inspect(next)
2010 fn size_hint(&self) -> (uint, Option<uint>) {
2011 self.iter.size_hint()
2015 #[unstable = "trait is unstable"]
2016 impl<'a, A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A>
2017 for Inspect<'a, A, T> {
2019 fn next_back(&mut self) -> Option<A> {
2020 let next = self.iter.next_back();
2021 self.do_inspect(next)
2025 #[experimental = "trait is experimental"]
2026 impl<'a, A, T: RandomAccessIterator<A>> RandomAccessIterator<A>
2027 for Inspect<'a, A, T> {
2029 fn indexable(&self) -> uint {
2030 self.iter.indexable()
2034 fn idx(&mut self, index: uint) -> Option<A> {
2035 let element = self.iter.idx(index);
2036 self.do_inspect(element)
2040 /// An iterator which passes mutable state to a closure and yields the result.
2042 /// # Example: The Fibonacci Sequence
2044 /// An iterator that yields sequential Fibonacci numbers, and stops on overflow.
2047 /// use std::iter::Unfold;
2048 /// use std::num::Int; // For `.checked_add()`
2050 /// // This iterator will yield up to the last Fibonacci number before the max value of `u32`.
2051 /// // You can simply change `u32` to `u64` in this line if you want higher values than that.
2052 /// let mut fibonacci = Unfold::new((Some(0u32), Some(1u32)), |&(ref mut x2, ref mut x1)| {
2053 /// // Attempt to get the next Fibonacci number
2054 /// // `x1` will be `None` if previously overflowed.
2055 /// let next = match (*x2, *x1) {
2056 /// (Some(x2), Some(x1)) => x2.checked_add(x1),
2060 /// // Shift left: ret <- x2 <- x1 <- next
2068 /// for i in fibonacci {
2069 /// println!("{}", i);
2073 pub struct Unfold<'a, A, St> {
2074 f: |&mut St|: 'a -> Option<A>,
2075 /// Internal state that will be passed to the closure on the next iteration
2080 impl<'a, A, St> Unfold<'a, A, St> {
2081 /// Creates a new iterator with the specified closure as the "iterator
2082 /// function" and an initial state to eventually pass to the closure
2084 pub fn new<'a>(initial_state: St, f: |&mut St|: 'a -> Option<A>)
2085 -> Unfold<'a, A, St> {
2088 state: initial_state
2094 impl<'a, A, St> Iterator<A> for Unfold<'a, A, St> {
2096 fn next(&mut self) -> Option<A> {
2097 (self.f)(&mut self.state)
2101 fn size_hint(&self) -> (uint, Option<uint>) {
2102 // no possible known bounds at this point
2107 /// An infinite iterator starting at `start` and advancing by `step` with each
2110 #[unstable = "may be renamed"]
2111 pub struct Counter<A> {
2112 /// The current state the counter is at (next value to be yielded)
2114 /// The amount that this iterator is stepping by
2118 /// Creates a new counter with the specified start/step
2120 #[unstable = "may be renamed"]
2121 pub fn count<A>(start: A, step: A) -> Counter<A> {
2122 Counter{state: start, step: step}
2125 #[unstable = "trait is unstable"]
2126 impl<A: Add<A, A> + Clone> Iterator<A> for Counter<A> {
2128 fn next(&mut self) -> Option<A> {
2129 let result = self.state.clone();
2130 self.state = self.state + self.step;
2135 fn size_hint(&self) -> (uint, Option<uint>) {
2136 (uint::MAX, None) // Too bad we can't specify an infinite lower bound
2140 /// An iterator over the range [start, stop)
2142 #[unstable = "may be refactored due to numerics reform or ops reform"]
2143 pub struct Range<A> {
2149 /// Returns an iterator over the given range [start, stop) (that is, starting
2150 /// at start (inclusive), and ending at stop (exclusive)).
2155 /// let array = [0, 1, 2, 3, 4];
2157 /// for i in range(0, 5u) {
2158 /// println!("{}", i);
2159 /// assert_eq!(i, array[i]);
2163 pub fn range<A: Int>(start: A, stop: A) -> Range<A> {
2171 // FIXME: #10414: Unfortunate type bound
2172 #[unstable = "trait is unstable"]
2173 impl<A: Int + ToPrimitive> Iterator<A> for Range<A> {
2175 fn next(&mut self) -> Option<A> {
2176 if self.state < self.stop {
2177 let result = self.state.clone();
2178 self.state = self.state + self.one;
2186 fn size_hint(&self) -> (uint, Option<uint>) {
2187 // This first checks if the elements are representable as i64. If they aren't, try u64 (to
2188 // handle cases like range(huge, huger)). We don't use uint/int because the difference of
2189 // the i64/u64 might lie within their range.
2190 let bound = match self.state.to_i64() {
2192 let sz = self.stop.to_i64().map(|b| b.checked_sub(a));
2194 Some(Some(bound)) => bound.to_uint(),
2198 None => match self.state.to_u64() {
2200 let sz = self.stop.to_u64().map(|b| b.checked_sub(a));
2202 Some(Some(bound)) => bound.to_uint(),
2211 Some(b) => (b, Some(b)),
2212 // Standard fallback for unbounded/unrepresentable bounds
2218 /// `Int` is required to ensure the range will be the same regardless of
2219 /// the direction it is consumed.
2220 #[unstable = "trait is unstable"]
2221 impl<A: Int + ToPrimitive> DoubleEndedIterator<A> for Range<A> {
2223 fn next_back(&mut self) -> Option<A> {
2224 if self.stop > self.state {
2225 self.stop = self.stop - self.one;
2226 Some(self.stop.clone())
2233 /// An iterator over the range [start, stop]
2235 #[unstable = "may be refactored due to numerics reform or ops reform"]
2236 pub struct RangeInclusive<A> {
2241 /// Return an iterator over the range [start, stop]
2243 #[unstable = "may be refactored due to numerics reform or ops reform"]
2244 pub fn range_inclusive<A: Int>(start: A, stop: A) -> RangeInclusive<A> {
2246 range: range(start, stop),
2251 #[unstable = "trait is unstable"]
2252 impl<A: Int + ToPrimitive> Iterator<A> for RangeInclusive<A> {
2254 fn next(&mut self) -> Option<A> {
2255 match self.range.next() {
2258 if !self.done && self.range.state == self.range.stop {
2260 Some(self.range.stop.clone())
2269 fn size_hint(&self) -> (uint, Option<uint>) {
2270 let (lo, hi) = self.range.size_hint();
2274 let lo = lo.saturating_add(1);
2276 Some(x) => x.checked_add(1),
2284 #[unstable = "trait is unstable"]
2285 impl<A: Int + ToPrimitive> DoubleEndedIterator<A> for RangeInclusive<A> {
2287 fn next_back(&mut self) -> Option<A> {
2288 if self.range.stop > self.range.state {
2289 let result = self.range.stop.clone();
2290 self.range.stop = self.range.stop - self.range.one;
2292 } else if !self.done && self.range.state == self.range.stop {
2294 Some(self.range.stop.clone())
2301 /// An iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2303 #[unstable = "may be refactored due to numerics reform or ops reform"]
2304 pub struct RangeStep<A> {
2311 /// Return an iterator over the range [start, stop) by `step`. It handles overflow by stopping.
2313 #[unstable = "may be refactored due to numerics reform or ops reform"]
2314 pub fn range_step<A: Int>(start: A, stop: A, step: A) -> RangeStep<A> {
2315 let rev = step < Int::zero();
2316 RangeStep{state: start, stop: stop, step: step, rev: rev}
2319 #[unstable = "trait is unstable"]
2320 impl<A: Int> Iterator<A> for RangeStep<A> {
2322 fn next(&mut self) -> Option<A> {
2323 if (self.rev && self.state > self.stop) || (!self.rev && self.state < self.stop) {
2324 let result = self.state;
2325 match self.state.checked_add(self.step) {
2326 Some(x) => self.state = x,
2327 None => self.state = self.stop.clone()
2336 /// An iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2338 #[unstable = "may be refactored due to numerics reform or ops reform"]
2339 pub struct RangeStepInclusive<A> {
2347 /// Return an iterator over the range [start, stop] by `step`. It handles overflow by stopping.
2349 #[unstable = "may be refactored due to numerics reform or ops reform"]
2350 pub fn range_step_inclusive<A: Int>(start: A, stop: A, step: A) -> RangeStepInclusive<A> {
2351 let rev = step < Int::zero();
2352 RangeStepInclusive {
2361 #[unstable = "trait is unstable"]
2362 impl<A: Int> Iterator<A> for RangeStepInclusive<A> {
2364 fn next(&mut self) -> Option<A> {
2365 if !self.done && ((self.rev && self.state >= self.stop) ||
2366 (!self.rev && self.state <= self.stop)) {
2367 let result = self.state;
2368 match self.state.checked_add(self.step) {
2369 Some(x) => self.state = x,
2370 None => self.done = true
2379 /// An iterator that repeats an element endlessly
2382 pub struct Repeat<A> {
2386 impl<A: Clone> Repeat<A> {
2387 /// Create a new `Repeat` that endlessly repeats the element `elt`.
2389 #[deprecated = "use iter::repeat instead"]
2390 pub fn new(elt: A) -> Repeat<A> {
2391 Repeat{element: elt}
2395 #[unstable = "trait is unstable"]
2396 impl<A: Clone> Iterator<A> for Repeat<A> {
2398 fn next(&mut self) -> Option<A> { self.idx(0) }
2400 fn size_hint(&self) -> (uint, Option<uint>) { (uint::MAX, None) }
2403 #[unstable = "trait is unstable"]
2404 impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
2406 fn next_back(&mut self) -> Option<A> { self.idx(0) }
2409 #[experimental = "trait is experimental"]
2410 impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
2412 fn indexable(&self) -> uint { uint::MAX }
2414 fn idx(&mut self, _: uint) -> Option<A> { Some(self.element.clone()) }
2417 type IterateState<'a, T> = (|T|: 'a -> T, Option<T>, bool);
2419 /// An iterator that repeatedly applies a given function, starting
2420 /// from a given seed value.
2422 pub type Iterate<'a, T> = Unfold<'a, T, IterateState<'a, T>>;
2424 /// Create a new iterator that produces an infinite sequence of
2425 /// repeated applications of the given function `f`.
2427 pub fn iterate<'a, T: Clone>(seed: T, f: |T|: 'a -> T) -> Iterate<'a, T> {
2428 Unfold::new((f, Some(seed), true), |st| {
2429 let &(ref mut f, ref mut val, ref mut first) = st;
2435 *val = Some((*f)(x))
2444 /// Create a new iterator that endlessly repeats the element `elt`.
2447 pub fn repeat<T: Clone>(elt: T) -> Repeat<T> {
2448 Repeat{element: elt}
2451 /// Functions for lexicographical ordering of sequences.
2453 /// Lexicographical ordering through `<`, `<=`, `>=`, `>` requires
2454 /// that the elements implement both `PartialEq` and `PartialOrd`.
2456 /// If two sequences are equal up until the point where one ends,
2457 /// the shorter sequence compares less.
2458 #[experimental = "likely to be removed after cmp reform"]
2461 use cmp::{Eq, Ord, PartialOrd, PartialEq};
2462 use cmp::Ordering::{Equal, Less, Greater};
2464 use option::Option::{Some, None};
2465 use super::Iterator;
2467 /// Compare `a` and `b` for equality using `Eq`
2468 pub fn equals<A: Eq, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2470 match (a.next(), b.next()) {
2471 (None, None) => return true,
2472 (None, _) | (_, None) => return false,
2473 (Some(x), Some(y)) => if x != y { return false },
2478 /// Order `a` and `b` lexicographically using `Ord`
2479 pub fn cmp<A: Ord, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> cmp::Ordering {
2481 match (a.next(), b.next()) {
2482 (None, None) => return Equal,
2483 (None, _ ) => return Less,
2484 (_ , None) => return Greater,
2485 (Some(x), Some(y)) => match x.cmp(&y) {
2487 non_eq => return non_eq,
2493 /// Order `a` and `b` lexicographically using `PartialOrd`
2494 pub fn partial_cmp<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S)
2495 -> Option<cmp::Ordering> {
2497 match (a.next(), b.next()) {
2498 (None, None) => return Some(Equal),
2499 (None, _ ) => return Some(Less),
2500 (_ , None) => return Some(Greater),
2501 (Some(x), Some(y)) => match x.partial_cmp(&y) {
2503 non_eq => return non_eq,
2509 /// Compare `a` and `b` for equality (Using partial equality, `PartialEq`)
2510 pub fn eq<A, B, L, R>(mut a: L, mut b: R) -> bool where
2516 match (a.next(), b.next()) {
2517 (None, None) => return true,
2518 (None, _) | (_, None) => return false,
2519 (Some(x), Some(y)) => if !x.eq(&y) { return false },
2524 /// Compare `a` and `b` for nonequality (Using partial equality, `PartialEq`)
2525 pub fn ne<A, B, L, R>(mut a: L, mut b: R) -> bool where
2531 match (a.next(), b.next()) {
2532 (None, None) => return false,
2533 (None, _) | (_, None) => return true,
2534 (Some(x), Some(y)) => if x.ne(&y) { return true },
2539 /// Return `a` < `b` lexicographically (Using partial order, `PartialOrd`)
2540 pub fn lt<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2542 match (a.next(), b.next()) {
2543 (None, None) => return false,
2544 (None, _ ) => return true,
2545 (_ , None) => return false,
2546 (Some(x), Some(y)) => if x.ne(&y) { return x.lt(&y) },
2551 /// Return `a` <= `b` lexicographically (Using partial order, `PartialOrd`)
2552 pub fn le<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2554 match (a.next(), b.next()) {
2555 (None, None) => return true,
2556 (None, _ ) => return true,
2557 (_ , None) => return false,
2558 (Some(x), Some(y)) => if x.ne(&y) { return x.le(&y) },
2563 /// Return `a` > `b` lexicographically (Using partial order, `PartialOrd`)
2564 pub fn gt<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2566 match (a.next(), b.next()) {
2567 (None, None) => return false,
2568 (None, _ ) => return false,
2569 (_ , None) => return true,
2570 (Some(x), Some(y)) => if x.ne(&y) { return x.gt(&y) },
2575 /// Return `a` >= `b` lexicographically (Using partial order, `PartialOrd`)
2576 pub fn ge<A: PartialOrd, T: Iterator<A>, S: Iterator<A>>(mut a: T, mut b: S) -> bool {
2578 match (a.next(), b.next()) {
2579 (None, None) => return true,
2580 (None, _ ) => return false,
2581 (_ , None) => return true,
2582 (Some(x), Some(y)) => if x.ne(&y) { return x.ge(&y) },