2 #![crate_name="itertools"]
3 #![cfg_attr(not(feature = "use_std"), no_std)]
5 //! Itertools — extra iterator adaptors, functions and macros.
7 //! To use the iterator methods in this crate, import the [`Itertools` trait](./trait.Itertools.html):
10 //! use itertools::Itertools;
16 //! - Enabled by default.
17 //! - Disable to compile itertools using `#![no_std]`. This disables
18 //! any items that depend on collections (like `group_by`, `unique`,
19 //! `kmerge`, `join` and many more).
23 //! This version of itertools requires Rust 1.12 or later.
25 #![doc(html_root_url="https://docs.rs/itertools/0.7/")]
29 #[cfg(not(feature = "use_std"))]
30 extern crate core
as std
;
32 pub use either
::Either
;
34 use std
::iter
::{IntoIterator}
;
35 use std
::cmp
::Ordering
;
37 #[cfg(feature = "use_std")]
39 #[cfg(feature = "use_std")]
45 // for compatibility with no std and macros
47 pub use std
::iter
as __std_iter
;
49 /// The concrete iterator types.
70 #[cfg(feature = "use_std")]
71 pub use adaptors
::MultiProduct
;
72 #[cfg(feature = "use_std")]
73 pub use combinations
::Combinations
;
74 pub use cons_tuples_impl
::ConsTuples
;
75 pub use format
::{Format, FormatWith}
;
76 #[cfg(feature = "use_std")]
77 pub use groupbylazy
::{IntoChunks, Chunk, Chunks, GroupBy, Group, Groups}
;
78 pub use intersperse
::Intersperse
;
79 #[cfg(feature = "use_std")]
80 pub use kmerge_impl
::{KMerge, KMergeBy}
;
81 pub use merge_join
::MergeJoinBy
;
82 #[cfg(feature = "use_std")]
83 pub use multipeek_impl
::MultiPeek
;
84 pub use pad_tail
::PadUsing
;
85 pub use peeking_take_while
::PeekingTakeWhile
;
86 pub use process_results_impl
::ProcessResults
;
87 #[cfg(feature = "use_std")]
88 pub use put_back_n_impl
::PutBackN
;
89 #[cfg(feature = "use_std")]
90 pub use rciter_impl
::RcIter
;
91 pub use repeatn
::RepeatN
;
92 pub use sources
::{RepeatCall, Unfold, Iterate}
;
93 #[cfg(feature = "use_std")]
95 pub use tuple_impl
::{TupleBuffer, TupleWindows, Tuples}
;
96 #[cfg(feature = "use_std")]
97 pub use unique_impl
::{Unique, UniqueBy}
;
98 pub use with_position
::WithPosition
;
99 pub use zip_eq_impl
::ZipEq
;
100 pub use zip_longest
::ZipLongest
;
101 pub use ziptuple
::Zip
;
104 pub use concat_impl
::concat
;
105 pub use cons_tuples_impl
::cons_tuples
;
106 pub use diff
::diff_with
;
108 #[cfg(feature = "use_std")]
109 pub use kmerge_impl
::{kmerge_by}
;
110 pub use minmax
::MinMaxResult
;
111 pub use peeking_take_while
::PeekingNext
;
112 pub use process_results_impl
::process_results
;
113 pub use repeatn
::repeat_n
;
114 pub use sources
::{repeat_call, unfold, iterate}
;
115 pub use with_position
::Position
;
116 pub use ziptuple
::multizip
;
119 pub use either_or_both
::EitherOrBoth
;
125 mod cons_tuples_impl
;
126 #[cfg(feature = "use_std")]
130 #[cfg(feature = "use_std")]
133 #[cfg(feature = "use_std")]
137 #[cfg(feature = "use_std")]
140 mod peeking_take_while
;
141 mod process_results_impl
;
142 #[cfg(feature = "use_std")]
144 #[cfg(feature = "use_std")]
149 #[cfg(feature = "use_std")]
152 #[cfg(feature = "use_std")]
160 /// Create an iterator over the “cartesian product” of iterators.
162 /// Iterator element type is like `(A, B, ..., E)` if formed
163 /// from iterators `(I, J, ..., M)` with element types `I::Item = A`, `J::Item = B`, etc.
166 /// #[macro_use] extern crate itertools;
168 /// // Iterate over the coordinates of a 4 x 4 x 4 grid
169 /// // from (0, 0, 0), (0, 0, 1), .., (0, 1, 0), (0, 1, 1), .. etc until (3, 3, 3)
170 /// for (i, j, k) in iproduct!(0..4, 0..4, 0..4) {
176 /// **Note:** To enable the macros in this crate, use the `#[macro_use]`
177 /// attribute when importing the crate:
180 /// #[macro_use] extern crate itertools;
183 macro_rules
! iproduct
{
184 (@flatten $I
:expr
,) => (
187 (@flatten $I
:expr
, $J
:expr
, $
($K
:expr
,)*) => (
188 iproduct
!(@flatten $
crate::cons_tuples(iproduct
!($I
, $J
)), $
($K
,)*)
191 $
crate::__std_iter
::IntoIterator
::into_iter($I
)
193 ($I
:expr
, $J
:expr
) => (
194 $
crate::Itertools
::cartesian_product(iproduct
!($I
), iproduct
!($J
))
196 ($I
:expr
, $J
:expr
, $
($K
:expr
),+) => (
197 iproduct
!(@flatten iproduct
!($I
, $J
), $
($K
,)+)
202 /// Create an iterator running multiple iterators in lockstep.
204 /// The `izip!` iterator yields elements until any subiterator
207 /// This is a version of the standard ``.zip()`` that's supporting more than
208 /// two iterators. The iterator elment type is a tuple with one element
209 /// from each of the input iterators. Just like ``.zip()``, the iteration stops
210 /// when the shortest of the inputs reaches its end.
212 /// **Note:** The result of this macro is an iterator composed of
213 /// repeated `.zip()` and a `.map()`; it has an anonymous type.
214 /// Prefer this macro `izip!()` over [`multizip`] for the performance benefits
215 /// of using the standard library `.zip()`.
217 /// [`multizip`]: fn.multizip.html
220 /// #[macro_use] extern crate itertools;
223 /// // iterate over three sequences side-by-side
224 /// let mut results = [0, 0, 0, 0];
225 /// let inputs = [3, 7, 9, 6];
227 /// for (r, index, input) in izip!(&mut results, 0..10, &inputs) {
228 /// *r = index * 10 + input;
231 /// assert_eq!(results, [0 + 3, 10 + 7, 29, 36]);
235 /// **Note:** To enable the macros in this crate, use the `#[macro_use]`
236 /// attribute when importing the crate:
239 /// #[macro_use] extern crate itertools;
243 // @closure creates a tuple-flattening closure for .map() call. usage:
244 // @closure partial_pattern => partial_tuple , rest , of , iterators
245 // eg. izip!( @closure ((a, b), c) => (a, b, c) , dd , ee )
246 ( @closure $p
:pat
=> $tup
:expr
) => {
250 // The "b" identifier is a different identifier on each recursion level thanks to hygiene.
251 ( @closure $p
:pat
=> ( $
($tup
:tt
)* ) , $_iter
:expr $
( , $tail
:expr
)* ) => {
252 izip
!(@
closure ($p
, b
) => ( $
($tup
)*, b
) $
( , $tail
)*)
255 ( $first
:expr $
( , $rest
:expr
)* $
(,)* ) => {
256 $
crate::__std_iter
::IntoIterator
::into_iter($first
)
261 izip
!(@closure a
=> (a
) $
( , $rest
)*)
266 /// The trait `Itertools`: extra iterator adaptors and methods for iterators.
268 /// This trait defines a number of methods. They are divided into two groups:
270 /// * *Adaptors* take an iterator and parameter as input, and return
271 /// a new iterator value. These are listed first in the trait. An example
272 /// of an adaptor is [`.interleave()`](#method.interleave)
274 /// * *Regular methods* are those that don't return iterators and instead
275 /// return a regular value of some other kind.
276 /// [`.next_tuple()`](#method.next_tuple) is an example and the first regular
277 /// method in the list.
278 pub trait Itertools
: Iterator
{
281 /// Alternate elements from two iterators until both have run out.
283 /// Iterator element type is `Self::Item`.
285 /// This iterator is *fused*.
288 /// use itertools::Itertools;
290 /// let it = (1..7).interleave(vec![-1, -2]);
291 /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3, 4, 5, 6]);
293 fn interleave
<J
>(self, other
: J
) -> Interleave
<Self, J
::IntoIter
>
294 where J
: IntoIterator
<Item
= Self::Item
>,
297 interleave(self, other
)
300 /// Alternate elements from two iterators until at least one of them has run
303 /// Iterator element type is `Self::Item`.
306 /// use itertools::Itertools;
308 /// let it = (1..7).interleave_shortest(vec![-1, -2]);
309 /// itertools::assert_equal(it, vec![1, -1, 2, -2, 3]);
311 fn interleave_shortest
<J
>(self, other
: J
) -> InterleaveShortest
<Self, J
::IntoIter
>
312 where J
: IntoIterator
<Item
= Self::Item
>,
315 adaptors
::interleave_shortest(self, other
.into_iter())
318 /// An iterator adaptor to insert a particular value
319 /// between each element of the adapted iterator.
321 /// Iterator element type is `Self::Item`.
323 /// This iterator is *fused*.
326 /// use itertools::Itertools;
328 /// itertools::assert_equal((0..3).intersperse(8), vec![0, 8, 1, 8, 2]);
330 fn intersperse(self, element
: Self::Item
) -> Intersperse
<Self>
334 intersperse
::intersperse(self, element
)
337 /// Create an iterator which iterates over both this and the specified
338 /// iterator simultaneously, yielding pairs of two optional elements.
340 /// This iterator is *fused*.
342 /// As long as neither input iterator is exhausted yet, it yields two values
343 /// via `EitherOrBoth::Both`.
345 /// When the parameter iterator is exhausted, it only yields a value from the
346 /// `self` iterator via `EitherOrBoth::Left`.
348 /// When the `self` iterator is exhausted, it only yields a value from the
349 /// parameter iterator via `EitherOrBoth::Right`.
351 /// When both iterators return `None`, all further invocations of `.next()`
352 /// will return `None`.
354 /// Iterator element type is
355 /// [`EitherOrBoth<Self::Item, J::Item>`](enum.EitherOrBoth.html).
358 /// use itertools::EitherOrBoth::{Both, Right};
359 /// use itertools::Itertools;
360 /// let it = (0..1).zip_longest(1..3);
361 /// itertools::assert_equal(it, vec![Both(0, 1), Right(2)]);
364 fn zip_longest
<J
>(self, other
: J
) -> ZipLongest
<Self, J
::IntoIter
>
365 where J
: IntoIterator
,
368 zip_longest
::zip_longest(self, other
.into_iter())
371 /// Create an iterator which iterates over both this and the specified
372 /// iterator simultaneously, yielding pairs of elements.
374 /// **Panics** if the iterators reach an end and they are not of equal
377 fn zip_eq
<J
>(self, other
: J
) -> ZipEq
<Self, J
::IntoIter
>
378 where J
: IntoIterator
,
384 /// A “meta iterator adaptor”. Its closure recives a reference to the
385 /// iterator and may pick off as many elements as it likes, to produce the
386 /// next iterator element.
388 /// Iterator element type is `B`.
391 /// use itertools::Itertools;
393 /// // An adaptor that gathers elements in pairs
394 /// let pit = (0..4).batching(|it| {
395 /// match it.next() {
397 /// Some(x) => match it.next() {
399 /// Some(y) => Some((x, y)),
404 /// itertools::assert_equal(pit, vec![(0, 1), (2, 3)]);
407 fn batching
<B
, F
>(self, f
: F
) -> Batching
<Self, F
>
408 where F
: FnMut(&mut Self) -> Option
<B
>,
411 adaptors
::batching(self, f
)
414 /// Return an *iterable* that can group iterator elements.
415 /// Consecutive elements that map to the same key (“runs”), are assigned
416 /// to the same group.
418 /// `GroupBy` is the storage for the lazy grouping operation.
420 /// If the groups are consumed in order, or if each group's iterator is
421 /// dropped without keeping it around, then `GroupBy` uses no
422 /// allocations. It needs allocations only if several group iterators
423 /// are alive at the same time.
425 /// This type implements `IntoIterator` (it is **not** an iterator
426 /// itself), because the group iterators need to borrow from this
427 /// value. It should be stored in a local variable or temporary and
430 /// Iterator element type is `(K, Group)`: the group's key and the
434 /// use itertools::Itertools;
436 /// // group data into runs of larger than zero or not.
437 /// let data = vec![1, 3, -2, -2, 1, 0, 1, 2];
438 /// // groups: |---->|------>|--------->|
440 /// // Note: The `&` is significant here, `GroupBy` is iterable
441 /// // only by reference. You can also call `.into_iter()` explicitly.
442 /// for (key, group) in &data.into_iter().group_by(|elt| *elt >= 0) {
443 /// // Check that the sum of each group is +/- 4.
444 /// assert_eq!(4, group.sum::<i32>().abs());
447 #[cfg(feature = "use_std")]
448 fn group_by
<K
, F
>(self, key
: F
) -> GroupBy
<K
, Self, F
>
450 F
: FnMut(&Self::Item
) -> K
,
453 groupbylazy
::new(self, key
)
456 /// Return an *iterable* that can chunk the iterator.
458 /// Yield subiterators (chunks) that each yield a fixed number elements,
459 /// determined by `size`. The last chunk will be shorter if there aren't
462 /// `IntoChunks` is based on `GroupBy`: it is iterable (implements
463 /// `IntoIterator`, **not** `Iterator`), and it only buffers if several
464 /// chunk iterators are alive at the same time.
466 /// Iterator element type is `Chunk`, each chunk's iterator.
468 /// **Panics** if `size` is 0.
471 /// use itertools::Itertools;
473 /// let data = vec![1, 1, 2, -2, 6, 0, 3, 1];
474 /// //chunk size=3 |------->|-------->|--->|
476 /// // Note: The `&` is significant here, `IntoChunks` is iterable
477 /// // only by reference. You can also call `.into_iter()` explicitly.
478 /// for chunk in &data.into_iter().chunks(3) {
479 /// // Check that the sum of each chunk is 4.
480 /// assert_eq!(4, chunk.sum());
483 #[cfg(feature = "use_std")]
484 fn chunks(self, size
: usize) -> IntoChunks
<Self>
488 groupbylazy
::new_chunks(self, size
)
491 /// Return an iterator over all contiguous windows producing tuples of
492 /// a specific size (up to 4).
494 /// `tuple_windows` clones the iterator elements so that they can be
495 /// part of successive windows, this makes it most suited for iterators
496 /// of references and other values that are cheap to copy.
499 /// use itertools::Itertools;
500 /// let mut v = Vec::new();
501 /// for (a, b) in (1..5).tuple_windows() {
504 /// assert_eq!(v, vec![(1, 2), (2, 3), (3, 4)]);
506 /// let mut it = (1..5).tuple_windows();
507 /// assert_eq!(Some((1, 2, 3)), it.next());
508 /// assert_eq!(Some((2, 3, 4)), it.next());
509 /// assert_eq!(None, it.next());
511 /// // this requires a type hint
512 /// let it = (1..5).tuple_windows::<(_, _, _)>();
513 /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
515 /// // you can also specify the complete type
516 /// use itertools::TupleWindows;
517 /// use std::ops::Range;
519 /// let it: TupleWindows<Range<u32>, (u32, u32, u32)> = (1..5).tuple_windows();
520 /// itertools::assert_equal(it, vec![(1, 2, 3), (2, 3, 4)]);
522 fn tuple_windows
<T
>(self) -> TupleWindows
<Self, T
>
523 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
524 T
: tuple_impl
::TupleCollect
,
527 tuple_impl
::tuple_windows(self)
530 /// Return an iterator that groups the items in tuples of a specific size
533 /// See also the method [`.next_tuple()`](#method.next_tuple).
536 /// use itertools::Itertools;
537 /// let mut v = Vec::new();
538 /// for (a, b) in (1..5).tuples() {
541 /// assert_eq!(v, vec![(1, 2), (3, 4)]);
543 /// let mut it = (1..7).tuples();
544 /// assert_eq!(Some((1, 2, 3)), it.next());
545 /// assert_eq!(Some((4, 5, 6)), it.next());
546 /// assert_eq!(None, it.next());
548 /// // this requires a type hint
549 /// let it = (1..7).tuples::<(_, _, _)>();
550 /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
552 /// // you can also specify the complete type
553 /// use itertools::Tuples;
554 /// use std::ops::Range;
556 /// let it: Tuples<Range<u32>, (u32, u32, u32)> = (1..7).tuples();
557 /// itertools::assert_equal(it, vec![(1, 2, 3), (4, 5, 6)]);
560 /// See also [`Tuples::into_buffer`](structs/struct.Tuples.html#method.into_buffer).
561 fn tuples
<T
>(self) -> Tuples
<Self, T
>
562 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
563 T
: tuple_impl
::TupleCollect
565 tuple_impl
::tuples(self)
568 /// Split into an iterator pair that both yield all elements from
569 /// the original iterator.
571 /// **Note:** If the iterator is clonable, prefer using that instead
572 /// of using this method. It is likely to be more efficient.
574 /// Iterator element type is `Self::Item`.
577 /// use itertools::Itertools;
578 /// let xs = vec![0, 1, 2, 3];
580 /// let (mut t1, t2) = xs.into_iter().tee();
581 /// itertools::assert_equal(t1.next(), Some(0));
582 /// itertools::assert_equal(t2, 0..4);
583 /// itertools::assert_equal(t1, 1..4);
585 #[cfg(feature = "use_std")]
586 fn tee(self) -> (Tee
<Self>, Tee
<Self>)
593 /// Return an iterator adaptor that steps `n` elements in the base iterator
594 /// for each iteration.
596 /// The iterator steps by yielding the next element from the base iterator,
597 /// then skipping forward `n - 1` elements.
599 /// Iterator element type is `Self::Item`.
601 /// **Panics** if the step is 0.
604 /// use itertools::Itertools;
606 /// let it = (0..8).step(3);
607 /// itertools::assert_equal(it, vec![0, 3, 6]);
609 fn step(self, n
: usize) -> Step
<Self>
612 adaptors
::step(self, n
)
615 /// Return an iterator adaptor that applies the provided closure
616 /// to every `Result::Ok` value. `Result::Err` values are
620 /// use itertools::Itertools;
622 /// let input = vec![Ok(41), Err(false), Ok(11)];
623 /// let it = input.into_iter().map_results(|i| i + 1);
624 /// itertools::assert_equal(it, vec![Ok(42), Err(false), Ok(12)]);
626 fn map_results
<F
, T
, U
, E
>(self, f
: F
) -> MapResults
<Self, F
>
627 where Self: Iterator
<Item
= Result
<T
, E
>> + Sized
,
630 adaptors
::map_results(self, f
)
633 /// Return an iterator adaptor that merges the two base iterators in
634 /// ascending order. If both base iterators are sorted (ascending), the
635 /// result is sorted.
637 /// Iterator element type is `Self::Item`.
640 /// use itertools::Itertools;
642 /// let a = (0..11).step(3);
643 /// let b = (0..11).step(5);
644 /// let it = a.merge(b);
645 /// itertools::assert_equal(it, vec![0, 0, 3, 5, 6, 9, 10]);
647 fn merge
<J
>(self, other
: J
) -> Merge
<Self, J
::IntoIter
>
649 Self::Item
: PartialOrd
,
650 J
: IntoIterator
<Item
= Self::Item
>
655 /// Return an iterator adaptor that merges the two base iterators in order.
656 /// This is much like `.merge()` but allows for a custom ordering.
658 /// This can be especially useful for sequences of tuples.
660 /// Iterator element type is `Self::Item`.
663 /// use itertools::Itertools;
665 /// let a = (0..).zip("bc".chars());
666 /// let b = (0..).zip("ad".chars());
667 /// let it = a.merge_by(b, |x, y| x.1 <= y.1);
668 /// itertools::assert_equal(it, vec![(0, 'a'), (0, 'b'), (1, 'c'), (1, 'd')]);
671 fn merge_by
<J
, F
>(self, other
: J
, is_first
: F
) -> MergeBy
<Self, J
::IntoIter
, F
>
673 J
: IntoIterator
<Item
= Self::Item
>,
674 F
: FnMut(&Self::Item
, &Self::Item
) -> bool
676 adaptors
::merge_by_new(self, other
.into_iter(), is_first
)
679 /// Create an iterator that merges items from both this and the specified
680 /// iterator in ascending order.
682 /// It chooses whether to pair elements based on the `Ordering` returned by the
683 /// specified compare function. At any point, inspecting the tip of the
684 /// iterators `I` and `J` as items `i` of type `I::Item` and `j` of type
685 /// `J::Item` respectively, the resulting iterator will:
687 /// - Emit `EitherOrBoth::Left(i)` when `i < j`,
688 /// and remove `i` from its source iterator
689 /// - Emit `EitherOrBoth::Right(j)` when `i > j`,
690 /// and remove `j` from its source iterator
691 /// - Emit `EitherOrBoth::Both(i, j)` when `i == j`,
692 /// and remove both `i` and `j` from their respective source iterators
695 /// use itertools::Itertools;
696 /// use itertools::EitherOrBoth::{Left, Right, Both};
698 /// let ki = (0..10).step(3);
699 /// let ku = (0..10).step(5);
700 /// let ki_ku = ki.merge_join_by(ku, |i, j| i.cmp(j)).map(|either| {
703 /// Right(_) => "Ku",
704 /// Both(_, _) => "KiKu"
708 /// itertools::assert_equal(ki_ku, vec!["KiKu", "Ki", "Ku", "Ki", "Ki"]);
711 fn merge_join_by
<J
, F
>(self, other
: J
, cmp_fn
: F
) -> MergeJoinBy
<Self, J
::IntoIter
, F
>
712 where J
: IntoIterator
,
713 F
: FnMut(&Self::Item
, &J
::Item
) -> std
::cmp
::Ordering
,
716 merge_join_by(self, other
, cmp_fn
)
720 /// Return an iterator adaptor that flattens an iterator of iterators by
721 /// merging them in ascending order.
723 /// If all base iterators are sorted (ascending), the result is sorted.
725 /// Iterator element type is `Self::Item`.
728 /// use itertools::Itertools;
730 /// let a = (0..6).step(3);
731 /// let b = (1..6).step(3);
732 /// let c = (2..6).step(3);
733 /// let it = vec![a, b, c].into_iter().kmerge();
734 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5]);
736 #[cfg(feature = "use_std")]
737 fn kmerge(self) -> KMerge
<<Self::Item
as IntoIterator
>::IntoIter
>
739 Self::Item
: IntoIterator
,
740 <Self::Item
as IntoIterator
>::Item
: PartialOrd
,
745 /// Return an iterator adaptor that flattens an iterator of iterators by
746 /// merging them according to the given closure.
748 /// The closure `first` is called with two elements *a*, *b* and should
749 /// return `true` if *a* is ordered before *b*.
751 /// If all base iterators are sorted according to `first`, the result is
754 /// Iterator element type is `Self::Item`.
757 /// use itertools::Itertools;
759 /// let a = vec![-1f64, 2., 3., -5., 6., -7.];
760 /// let b = vec![0., 2., -4.];
761 /// let mut it = vec![a, b].into_iter().kmerge_by(|a, b| a.abs() < b.abs());
762 /// assert_eq!(it.next(), Some(0.));
763 /// assert_eq!(it.last(), Some(-7.));
765 #[cfg(feature = "use_std")]
766 fn kmerge_by
<F
>(self, first
: F
)
767 -> KMergeBy
<<Self::Item
as IntoIterator
>::IntoIter
, F
>
769 Self::Item
: IntoIterator
,
770 F
: FnMut(&<Self::Item
as IntoIterator
>::Item
,
771 &<Self::Item
as IntoIterator
>::Item
) -> bool
773 kmerge_by(self, first
)
776 /// Return an iterator adaptor that iterates over the cartesian product of
777 /// the element sets of two iterators `self` and `J`.
779 /// Iterator element type is `(Self::Item, J::Item)`.
782 /// use itertools::Itertools;
784 /// let it = (0..2).cartesian_product("αβ".chars());
785 /// itertools::assert_equal(it, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]);
787 fn cartesian_product
<J
>(self, other
: J
) -> Product
<Self, J
::IntoIter
>
793 adaptors
::cartesian_product(self, other
.into_iter())
796 /// Return an iterator adaptor that iterates over the cartesian product of
797 /// all subiterators returned by meta-iterator `self`.
799 /// All provided iterators must yield the same `Item` type. To generate
800 /// the product of iterators yielding multiple types, use the
801 /// [`iproduct`](macro.iproduct.html) macro instead.
804 /// The iterator element type is `Vec<T>`, where `T` is the iterator element
805 /// of the subiterators.
808 /// use itertools::Itertools;
809 /// let mut multi_prod = (0..3).map(|i| (i * 2)..(i * 2 + 2))
810 /// .multi_cartesian_product();
811 /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 4]));
812 /// assert_eq!(multi_prod.next(), Some(vec![0, 2, 5]));
813 /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 4]));
814 /// assert_eq!(multi_prod.next(), Some(vec![0, 3, 5]));
815 /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 4]));
816 /// assert_eq!(multi_prod.next(), Some(vec![1, 2, 5]));
817 /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 4]));
818 /// assert_eq!(multi_prod.next(), Some(vec![1, 3, 5]));
819 /// assert_eq!(multi_prod.next(), None);
821 #[cfg(feature = "use_std")]
822 fn multi_cartesian_product(self) -> MultiProduct
<<Self::Item
as IntoIterator
>::IntoIter
>
823 where Self: Iterator
+ Sized
,
824 Self::Item
: IntoIterator
,
825 <Self::Item
as IntoIterator
>::IntoIter
: Clone
,
826 <Self::Item
as IntoIterator
>::Item
: Clone
828 adaptors
::multi_cartesian_product(self)
831 /// Return an iterator adaptor that uses the passed-in closure to
832 /// optionally merge together consecutive elements.
834 /// The closure `f` is passed two elements, `previous` and `current` and may
835 /// return either (1) `Ok(combined)` to merge the two values or
836 /// (2) `Err((previous', current'))` to indicate they can't be merged.
837 /// In (2), the value `previous'` is emitted by the iterator.
838 /// Either (1) `combined` or (2) `current'` becomes the previous value
839 /// when coalesce continues with the next pair of elements to merge. The
840 /// value that remains at the end is also emitted by the iterator.
842 /// Iterator element type is `Self::Item`.
844 /// This iterator is *fused*.
847 /// use itertools::Itertools;
849 /// // sum same-sign runs together
850 /// let data = vec![-1., -2., -3., 3., 1., 0., -1.];
851 /// itertools::assert_equal(data.into_iter().coalesce(|x, y|
852 /// if (x >= 0.) == (y >= 0.) {
857 /// vec![-6., 4., -1.]);
859 fn coalesce
<F
>(self, f
: F
) -> Coalesce
<Self, F
>
861 F
: FnMut(Self::Item
, Self::Item
)
862 -> Result
<Self::Item
, (Self::Item
, Self::Item
)>
864 adaptors
::coalesce(self, f
)
867 /// Remove duplicates from sections of consecutive identical elements.
868 /// If the iterator is sorted, all elements will be unique.
870 /// Iterator element type is `Self::Item`.
872 /// This iterator is *fused*.
875 /// use itertools::Itertools;
877 /// let data = vec![1., 1., 2., 3., 3., 2., 2.];
878 /// itertools::assert_equal(data.into_iter().dedup(),
879 /// vec![1., 2., 3., 2.]);
881 fn dedup(self) -> Dedup
<Self>
883 Self::Item
: PartialEq
,
885 adaptors
::dedup(self)
888 /// Return an iterator adaptor that filters out elements that have
889 /// already been produced once during the iteration. Duplicates
890 /// are detected using hash and equality.
892 /// Clones of visited elements are stored in a hash set in the
896 /// use itertools::Itertools;
898 /// let data = vec![10, 20, 30, 20, 40, 10, 50];
899 /// itertools::assert_equal(data.into_iter().unique(),
900 /// vec![10, 20, 30, 40, 50]);
902 #[cfg(feature = "use_std")]
903 fn unique(self) -> Unique
<Self>
905 Self::Item
: Clone
+ Eq
+ Hash
907 unique_impl
::unique(self)
910 /// Return an iterator adaptor that filters out elements that have
911 /// already been produced once during the iteration.
913 /// Duplicates are detected by comparing the key they map to
914 /// with the keying function `f` by hash and equality.
915 /// The keys are stored in a hash set in the iterator.
918 /// use itertools::Itertools;
920 /// let data = vec!["a", "bb", "aa", "c", "ccc"];
921 /// itertools::assert_equal(data.into_iter().unique_by(|s| s.len()),
922 /// vec!["a", "bb", "ccc"]);
924 #[cfg(feature = "use_std")]
925 fn unique_by
<V
, F
>(self, f
: F
) -> UniqueBy
<Self, V
, F
>
928 F
: FnMut(&Self::Item
) -> V
930 unique_impl
::unique_by(self, f
)
933 /// Return an iterator adaptor that borrows from this iterator and
934 /// takes items while the closure `accept` returns `true`.
936 /// This adaptor can only be used on iterators that implement `PeekingNext`
937 /// like `.peekable()`, `put_back` and a few other collection iterators.
939 /// The last and rejected element (first `false`) is still available when
940 /// `peeking_take_while` is done.
943 /// See also [`.take_while_ref()`](#method.take_while_ref)
944 /// which is a similar adaptor.
945 fn peeking_take_while
<F
>(&mut self, accept
: F
) -> PeekingTakeWhile
<Self, F
>
946 where Self: Sized
+ PeekingNext
,
947 F
: FnMut(&Self::Item
) -> bool
,
949 peeking_take_while
::peeking_take_while(self, accept
)
952 /// Return an iterator adaptor that borrows from a `Clone`-able iterator
953 /// to only pick off elements while the predicate `accept` returns `true`.
955 /// It uses the `Clone` trait to restore the original iterator so that the
956 /// last and rejected element (first `false`) is still available when
957 /// `take_while_ref` is done.
960 /// use itertools::Itertools;
962 /// let mut hexadecimals = "0123456789abcdef".chars();
964 /// let decimals = hexadecimals.take_while_ref(|c| c.is_numeric())
965 /// .collect::<String>();
966 /// assert_eq!(decimals, "0123456789");
967 /// assert_eq!(hexadecimals.next(), Some('a'));
970 fn take_while_ref
<F
>(&mut self, accept
: F
) -> TakeWhileRef
<Self, F
>
972 F
: FnMut(&Self::Item
) -> bool
974 adaptors
::take_while_ref(self, accept
)
977 /// Return an iterator adaptor that filters `Option<A>` iterator elements
978 /// and produces `A`. Stops on the first `None` encountered.
980 /// Iterator element type is `A`, the unwrapped element.
983 /// use itertools::Itertools;
985 /// // List all hexadecimal digits
986 /// itertools::assert_equal(
987 /// (0..).map(|i| std::char::from_digit(i, 16)).while_some(),
988 /// "0123456789abcdef".chars());
991 fn while_some
<A
>(self) -> WhileSome
<Self>
992 where Self: Sized
+ Iterator
<Item
= Option
<A
>>
994 adaptors
::while_some(self)
997 /// Return an iterator adaptor that iterates over the combinations of the
998 /// elements from an iterator.
1000 /// Iterator element can be any homogeneous tuple of type `Self::Item` with
1004 /// use itertools::Itertools;
1006 /// let mut v = Vec::new();
1007 /// for (a, b) in (1..5).tuple_combinations() {
1010 /// assert_eq!(v, vec![(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]);
1012 /// let mut it = (1..5).tuple_combinations();
1013 /// assert_eq!(Some((1, 2, 3)), it.next());
1014 /// assert_eq!(Some((1, 2, 4)), it.next());
1015 /// assert_eq!(Some((1, 3, 4)), it.next());
1016 /// assert_eq!(Some((2, 3, 4)), it.next());
1017 /// assert_eq!(None, it.next());
1019 /// // this requires a type hint
1020 /// let it = (1..5).tuple_combinations::<(_, _, _)>();
1021 /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1023 /// // you can also specify the complete type
1024 /// use itertools::TupleCombinations;
1025 /// use std::ops::Range;
1027 /// let it: TupleCombinations<Range<u32>, (u32, u32, u32)> = (1..5).tuple_combinations();
1028 /// itertools::assert_equal(it, vec![(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]);
1030 fn tuple_combinations
<T
>(self) -> TupleCombinations
<Self, T
>
1031 where Self: Sized
+ Clone
,
1033 T
: adaptors
::HasCombination
<Self>,
1035 adaptors
::tuple_combinations(self)
1038 /// Return an iterator adaptor that iterates over the `n`-length combinations of
1039 /// the elements from an iterator.
1041 /// Iterator element type is `Vec<Self::Item>`. The iterator produces a new Vec per iteration,
1042 /// and clones the iterator elements.
1045 /// use itertools::Itertools;
1047 /// let it = (1..5).combinations(3);
1048 /// itertools::assert_equal(it, vec![
1055 #[cfg(feature = "use_std")]
1056 fn combinations(self, n
: usize) -> Combinations
<Self>
1060 combinations
::combinations(self, n
)
1063 /// Return an iterator adaptor that pads the sequence to a minimum length of
1064 /// `min` by filling missing elements using a closure `f`.
1066 /// Iterator element type is `Self::Item`.
1069 /// use itertools::Itertools;
1071 /// let it = (0..5).pad_using(10, |i| 2*i);
1072 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 10, 12, 14, 16, 18]);
1074 /// let it = (0..10).pad_using(5, |i| 2*i);
1075 /// itertools::assert_equal(it, vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
1077 /// let it = (0..5).pad_using(10, |i| 2*i).rev();
1078 /// itertools::assert_equal(it, vec![18, 16, 14, 12, 10, 4, 3, 2, 1, 0]);
1080 fn pad_using
<F
>(self, min
: usize, f
: F
) -> PadUsing
<Self, F
>
1082 F
: FnMut(usize) -> Self::Item
1084 pad_tail
::pad_using(self, min
, f
)
1087 /// Unravel a nested iterator.
1089 /// This is more or less equivalent to `.flat_map` with an identity
1093 /// use itertools::Itertools;
1095 /// let data = vec![vec![1, 2, 3], vec![4, 5, 6]];
1096 /// let flattened = data.iter().flatten();
1098 /// itertools::assert_equal(flattened, &[1, 2, 3, 4, 5, 6]);
1100 fn flatten(self) -> Flatten
<Self, <Self::Item
as IntoIterator
>::IntoIter
>
1102 Self::Item
: IntoIterator
1104 adaptors
::flatten(self)
1107 /// Return an iterator adaptor that wraps each element in a `Position` to
1108 /// ease special-case handling of the first or last elements.
1110 /// Iterator element type is
1111 /// [`Position<Self::Item>`](enum.Position.html)
1114 /// use itertools::{Itertools, Position};
1116 /// let it = (0..4).with_position();
1117 /// itertools::assert_equal(it,
1118 /// vec![Position::First(0),
1119 /// Position::Middle(1),
1120 /// Position::Middle(2),
1121 /// Position::Last(3)]);
1123 /// let it = (0..1).with_position();
1124 /// itertools::assert_equal(it, vec![Position::Only(0)]);
1126 fn with_position(self) -> WithPosition
<Self>
1129 with_position
::with_position(self)
1132 /// Return an iterator adaptor that yields the indices of all elements
1133 /// satisfying a predicate, counted from the start of the iterator.
1135 /// Equivalent to `iter.enumerate().filter(|(_, v)| predicate(v)).map(|(i, _)| i)`.
1138 /// use itertools::Itertools;
1140 /// let data = vec![1, 2, 3, 3, 4, 6, 7, 9];
1141 /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 0), vec![1, 4, 5]);
1143 /// itertools::assert_equal(data.iter().positions(|v| v % 2 == 1).rev(), vec![7, 6, 3, 2, 0]);
1145 fn positions
<P
>(self, predicate
: P
) -> Positions
<Self, P
>
1147 P
: FnMut(Self::Item
) -> bool
,
1149 adaptors
::positions(self, predicate
)
1152 /// Return an iterator adaptor that applies a mutating function
1153 /// to each element before yielding it.
1156 /// use itertools::Itertools;
1158 /// let input = vec![vec![1], vec![3, 2, 1]];
1159 /// let it = input.into_iter().update(|mut v| v.push(0));
1160 /// itertools::assert_equal(it, vec![vec![1, 0], vec![3, 2, 1, 0]]);
1162 fn update
<F
>(self, updater
: F
) -> Update
<Self, F
>
1164 F
: FnMut(&mut Self::Item
),
1166 adaptors
::update(self, updater
)
1169 // non-adaptor methods
1170 /// Advances the iterator and returns the next items grouped in a tuple of
1171 /// a specific size (up to 4).
1173 /// If there are enough elements to be grouped in a tuple, then the tuple is
1174 /// returned inside `Some`, otherwise `None` is returned.
1177 /// use itertools::Itertools;
1179 /// let mut iter = 1..5;
1181 /// assert_eq!(Some((1, 2)), iter.next_tuple());
1183 fn next_tuple
<T
>(&mut self) -> Option
<T
>
1184 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
1185 T
: tuple_impl
::TupleCollect
1187 T
::collect_from_iter_no_buf(self)
1190 /// Collects all items from the iterator into a tuple of a specific size
1193 /// If the number of elements inside the iterator is **exactly** equal to
1194 /// the tuple size, then the tuple is returned inside `Some`, otherwise
1195 /// `None` is returned.
1198 /// use itertools::Itertools;
1200 /// let iter = 1..3;
1202 /// if let Some((x, y)) = iter.collect_tuple() {
1203 /// assert_eq!((x, y), (1, 2))
1205 /// panic!("Expected two elements")
1208 fn collect_tuple
<T
>(mut self) -> Option
<T
>
1209 where Self: Sized
+ Iterator
<Item
= T
::Item
>,
1210 T
: tuple_impl
::TupleCollect
1212 match self.next_tuple() {
1213 elt @
Some(_
) => match self.next() {
1222 /// Find the position and value of the first element satisfying a predicate.
1224 /// The iterator is not advanced past the first element found.
1227 /// use itertools::Itertools;
1229 /// let text = "Hα";
1230 /// assert_eq!(text.chars().find_position(|ch| ch.is_lowercase()), Some((1, 'α')));
1232 fn find_position
<P
>(&mut self, mut pred
: P
) -> Option
<(usize, Self::Item
)>
1233 where P
: FnMut(&Self::Item
) -> bool
1235 let mut index
= 0usize
;
1238 return Some((index
, elt
));
1245 /// Check whether all elements compare equal.
1247 /// Empty iterators are considered to have equal elements:
1250 /// use itertools::Itertools;
1252 /// let data = vec![1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5];
1253 /// assert!(!data.iter().all_equal());
1254 /// assert!(data[0..3].iter().all_equal());
1255 /// assert!(data[3..5].iter().all_equal());
1256 /// assert!(data[5..8].iter().all_equal());
1258 /// let data : Option<usize> = None;
1259 /// assert!(data.into_iter().all_equal());
1261 fn all_equal(&mut self) -> bool
1262 where Self::Item
: PartialEq
,
1264 self.dedup().nth(1).is_none()
1267 /// Consume the first `n` elements from the iterator eagerly,
1268 /// and return the same iterator again.
1270 /// It works similarly to *.skip(* `n` *)* except it is eager and
1271 /// preserves the iterator type.
1274 /// use itertools::Itertools;
1276 /// let mut iter = "αβγ".chars().dropping(2);
1277 /// itertools::assert_equal(iter, "γ".chars());
1280 /// *Fusing notes: if the iterator is exhausted by dropping,
1281 /// the result of calling `.next()` again depends on the iterator implementation.*
1282 fn dropping(mut self, n
: usize) -> Self
1291 /// Consume the last `n` elements from the iterator eagerly,
1292 /// and return the same iterator again.
1294 /// This is only possible on double ended iterators. `n` may be
1295 /// larger than the number of elements.
1297 /// Note: This method is eager, dropping the back elements immediately and
1298 /// preserves the iterator type.
1301 /// use itertools::Itertools;
1303 /// let init = vec![0, 3, 6, 9].into_iter().dropping_back(1);
1304 /// itertools::assert_equal(init, vec![0, 3, 6]);
1306 fn dropping_back(mut self, n
: usize) -> Self
1308 Self: DoubleEndedIterator
1311 (&mut self).rev().nth(n
- 1);
1316 /// Run the closure `f` eagerly on each element of the iterator.
1318 /// Consumes the iterator until its end.
1321 /// use std::sync::mpsc::channel;
1322 /// use itertools::Itertools;
1324 /// let (tx, rx) = channel();
1326 /// // use .foreach() to apply a function to each value -- sending it
1327 /// (0..5).map(|x| x * 2 + 1).foreach(|x| { tx.send(x).unwrap(); } );
1331 /// itertools::assert_equal(rx.iter(), vec![1, 3, 5, 7, 9]);
1333 fn foreach
<F
>(self, mut f
: F
)
1334 where F
: FnMut(Self::Item
),
1337 self.fold((), move |(), element
| f(element
))
1340 /// Combine all an iterator's elements into one element by using `Extend`.
1342 /// This combinator will extend the first item with each of the rest of the
1343 /// items of the iterator. If the iterator is empty, the default value of
1344 /// `I::Item` is returned.
1347 /// use itertools::Itertools;
1349 /// let input = vec![vec![1], vec![2, 3], vec![4, 5, 6]];
1350 /// assert_eq!(input.into_iter().concat(),
1351 /// vec![1, 2, 3, 4, 5, 6]);
1353 fn concat(self) -> Self::Item
1355 Self::Item
: Extend
<<<Self as Iterator
>::Item
as IntoIterator
>::Item
> + IntoIterator
+ Default
1360 /// `.collect_vec()` is simply a type specialization of `.collect()`,
1361 /// for convenience.
1362 #[cfg(feature = "use_std")]
1363 fn collect_vec(self) -> Vec
<Self::Item
>
1369 /// Assign to each reference in `self` from the `from` iterator,
1370 /// stopping at the shortest of the two iterators.
1372 /// The `from` iterator is queried for its next element before the `self`
1373 /// iterator, and if either is exhausted the method is done.
1375 /// Return the number of elements written.
1378 /// use itertools::Itertools;
1380 /// let mut xs = [0; 4];
1381 /// xs.iter_mut().set_from(1..);
1382 /// assert_eq!(xs, [1, 2, 3, 4]);
1385 fn set_from
<'a
, A
: 'a
, J
>(&mut self, from
: J
) -> usize
1386 where Self: Iterator
<Item
= &'a
mut A
>,
1387 J
: IntoIterator
<Item
= A
>
1393 Some(ptr
) => *ptr
= elt
,
1400 /// Combine all iterator elements into one String, seperated by `sep`.
1402 /// Use the `Display` implementation of each element.
1405 /// use itertools::Itertools;
1407 /// assert_eq!(["a", "b", "c"].iter().join(", "), "a, b, c");
1408 /// assert_eq!([1, 2, 3].iter().join(", "), "1, 2, 3");
1410 #[cfg(feature = "use_std")]
1411 fn join(&mut self, sep
: &str) -> String
1412 where Self::Item
: std
::fmt
::Display
1415 None
=> String
::new(),
1416 Some(first_elt
) => {
1417 // estimate lower bound of capacity needed
1418 let (lower
, _
) = self.size_hint();
1419 let mut result
= String
::with_capacity(sep
.len() * lower
);
1420 write
!(&mut result
, "{}", first_elt
).unwrap();
1422 result
.push_str(sep
);
1423 write
!(&mut result
, "{}", elt
).unwrap();
1430 /// Format all iterator elements, separated by `sep`.
1432 /// All elements are formatted (any formatting trait)
1433 /// with `sep` inserted between each element.
1435 /// **Panics** if the formatter helper is formatted more than once.
1438 /// use itertools::Itertools;
1440 /// let data = [1.1, 2.71828, -3.];
1442 /// format!("{:.2}", data.iter().format(", ")),
1443 /// "1.10, 2.72, -3.00");
1445 fn format(self, sep
: &str) -> Format
<Self>
1448 format
::new_format_default(self, sep
)
1451 /// Format all iterator elements, separated by `sep`.
1453 /// This is a customizable version of `.format()`.
1455 /// The supplied closure `format` is called once per iterator element,
1456 /// with two arguments: the element and a callback that takes a
1457 /// `&Display` value, i.e. any reference to type that implements `Display`.
1459 /// Using `&format_args!(...)` is the most versatile way to apply custom
1460 /// element formatting. The callback can be called multiple times if needed.
1462 /// **Panics** if the formatter helper is formatted more than once.
1465 /// use itertools::Itertools;
1467 /// let data = [1.1, 2.71828, -3.];
1468 /// let data_formatter = data.iter().format_with(", ", |elt, f| f(&format_args!("{:.2}", elt)));
1469 /// assert_eq!(format!("{}", data_formatter),
1470 /// "1.10, 2.72, -3.00");
1472 /// // .format_with() is recursively composable
1473 /// let matrix = [[1., 2., 3.],
1475 /// let matrix_formatter = matrix.iter().format_with("\n", |row, f| {
1476 /// f(&row.iter().format_with(", ", |elt, g| g(&elt)))
1478 /// assert_eq!(format!("{}", matrix_formatter),
1479 /// "1, 2, 3\n4, 5, 6");
1483 fn format_with
<F
>(self, sep
: &str, format
: F
) -> FormatWith
<Self, F
>
1485 F
: FnMut(Self::Item
, &mut FnMut(&fmt
::Display
) -> fmt
::Result
) -> fmt
::Result
,
1487 format
::new_format(self, sep
, format
)
1490 /// Fold `Result` values from an iterator.
1492 /// Only `Ok` values are folded. If no error is encountered, the folded
1493 /// value is returned inside `Ok`. Otherwise, the operation terminates
1494 /// and returns the first `Err` value it encounters. No iterator elements are
1495 /// consumed after the first error.
1497 /// The first accumulator value is the `start` parameter.
1498 /// Each iteration passes the accumulator value and the next value inside `Ok`
1499 /// to the fold function `f` and its return value becomes the new accumulator value.
1501 /// For example the sequence *Ok(1), Ok(2), Ok(3)* will result in a
1502 /// computation like this:
1505 /// let mut accum = start;
1506 /// accum = f(accum, 1);
1507 /// accum = f(accum, 2);
1508 /// accum = f(accum, 3);
1511 /// With a `start` value of 0 and an addition as folding function,
1512 /// this effetively results in *((0 + 1) + 2) + 3*
1515 /// use std::ops::Add;
1516 /// use itertools::Itertools;
1518 /// let values = [1, 2, -2, -1, 2, 1];
1521 /// .map(Ok::<_, ()>)
1522 /// .fold_results(0, Add::add),
1527 /// .map(|&x| if x >= 0 { Ok(x) } else { Err("Negative number") })
1528 /// .fold_results(0, Add::add)
1532 fn fold_results
<A
, E
, B
, F
>(&mut self, mut start
: B
, mut f
: F
) -> Result
<B
, E
>
1533 where Self: Iterator
<Item
= Result
<A
, E
>>,
1538 Ok(v
) => start
= f(start
, v
),
1539 Err(u
) => return Err(u
),
1545 /// Fold `Option` values from an iterator.
1547 /// Only `Some` values are folded. If no `None` is encountered, the folded
1548 /// value is returned inside `Some`. Otherwise, the operation terminates
1549 /// and returns `None`. No iterator elements are consumed after the `None`.
1551 /// This is the `Option` equivalent to `fold_results`.
1554 /// use std::ops::Add;
1555 /// use itertools::Itertools;
1557 /// let mut values = vec![Some(1), Some(2), Some(-2)].into_iter();
1558 /// assert_eq!(values.fold_options(5, Add::add), Some(5 + 1 + 2 - 2));
1560 /// let mut more_values = vec![Some(2), None, Some(0)].into_iter();
1561 /// assert!(more_values.fold_options(0, Add::add).is_none());
1562 /// assert_eq!(more_values.next().unwrap(), Some(0));
1564 fn fold_options
<A
, B
, F
>(&mut self, mut start
: B
, mut f
: F
) -> Option
<B
>
1565 where Self: Iterator
<Item
= Option
<A
>>,
1570 Some(v
) => start
= f(start
, v
),
1571 None
=> return None
,
1577 /// Accumulator of the elements in the iterator.
1579 /// Like `.fold()`, without a base case. If the iterator is
1580 /// empty, return `None`. With just one element, return it.
1581 /// Otherwise elements are accumulated in sequence using the closure `f`.
1584 /// use itertools::Itertools;
1586 /// assert_eq!((0..10).fold1(|x, y| x + y).unwrap_or(0), 45);
1587 /// assert_eq!((0..0).fold1(|x, y| x * y), None);
1589 fn fold1
<F
>(mut self, f
: F
) -> Option
<Self::Item
>
1590 where F
: FnMut(Self::Item
, Self::Item
) -> Self::Item
,
1593 self.next().map(move |x
| self.fold(x
, f
))
1596 /// An iterator method that applies a function, producing a single, final value.
1598 /// `fold_while()` is basically equivalent to `fold()` but with additional support for
1599 /// early exit via short-circuiting.
1602 /// use itertools::Itertools;
1603 /// use itertools::FoldWhile::{Continue, Done};
1605 /// let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1607 /// let mut result = 0;
1610 /// for i in &numbers {
1614 /// result = result + i;
1618 /// let result2 = numbers.iter().fold(0, |acc, x| {
1619 /// if *x > 5 { acc } else { acc + x }
1623 /// let result3 = numbers.iter().fold_while(0, |acc, x| {
1624 /// if *x > 5 { Done(acc) } else { Continue(acc + x) }
1625 /// }).into_inner();
1627 /// // they're the same
1628 /// assert_eq!(result, result2);
1629 /// assert_eq!(result2, result3);
1632 /// The big difference between the computations of `result2` and `result3` is that while
1633 /// `fold()` called the provided closure for every item of the callee iterator,
1634 /// `fold_while()` actually stopped iterating as soon as it encountered `Fold::Done(_)`.
1635 fn fold_while
<B
, F
>(&mut self, init
: B
, mut f
: F
) -> FoldWhile
<B
>
1637 F
: FnMut(B
, Self::Item
) -> FoldWhile
<B
>
1640 while let Some(item
) = self.next() {
1641 match f(acc
, item
) {
1642 FoldWhile
::Continue(res
) => acc
= res
,
1643 res @ FoldWhile
::Done(_
) => return res
,
1646 FoldWhile
::Continue(acc
)
1649 /// Collect all iterator elements into a sorted vector in ascending order.
1651 /// **Note:** This consumes the entire iterator, uses the
1652 /// `slice::sort_by()` method and returns the sorted vector.
1655 /// use itertools::Itertools;
1657 /// // sort the letters of the text in ascending order
1658 /// let text = "bdacfe";
1659 /// itertools::assert_equal(text.chars().sorted(),
1660 /// "abcdef".chars());
1662 #[cfg(feature = "use_std")]
1663 fn sorted(self) -> Vec
<Self::Item
>
1667 self.sorted_by(Ord
::cmp
)
1670 /// Collect all iterator elements into a sorted vector.
1672 /// **Note:** This consumes the entire iterator, uses the
1673 /// `slice::sort_by()` method and returns the sorted vector.
1676 /// use itertools::Itertools;
1678 /// // sort people in descending order by age
1679 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
1681 /// let oldest_people_first = people
1683 /// .sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
1685 /// .map(|(person, _age)| person);
1687 /// itertools::assert_equal(oldest_people_first,
1688 /// vec!["Jill", "Jack", "Jane", "John"]);
1690 #[cfg(feature = "use_std")]
1691 fn sorted_by
<F
>(self, cmp
: F
) -> Vec
<Self::Item
>
1693 F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
,
1695 let mut v
: Vec
<Self::Item
> = self.collect();
1701 /// Collect all iterator elements into a sorted vector.
1703 /// **Note:** This consumes the entire iterator, uses the
1704 /// `slice::sort_by_key()` method and returns the sorted vector.
1707 /// use itertools::Itertools;
1709 /// // sort people in descending order by age
1710 /// let people = vec![("Jane", 20), ("John", 18), ("Jill", 30), ("Jack", 27)];
1712 /// let oldest_people_first = people
1714 /// .sorted_by_key(|x| -x.1)
1716 /// .map(|(person, _age)| person);
1718 /// itertools::assert_equal(oldest_people_first,
1719 /// vec!["Jill", "Jack", "Jane", "John"]);
1721 #[cfg(feature = "use_std")]
1722 fn sorted_by_key
<K
, F
>(self, f
: F
) -> Vec
<Self::Item
>
1725 F
: FnMut(&Self::Item
) -> K
,
1727 let mut v
: Vec
<Self::Item
> = self.collect();
1733 /// Collect all iterator elements into one of two
1734 /// partitions. Unlike `Iterator::partition`, each partition may
1735 /// have a distinct type.
1738 /// use itertools::{Itertools, Either};
1740 /// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
1742 /// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
1744 /// .partition_map(|r| {
1746 /// Ok(v) => Either::Left(v),
1747 /// Err(v) => Either::Right(v),
1751 /// assert_eq!(successes, [1, 2]);
1752 /// assert_eq!(failures, [false, true]);
1754 fn partition_map
<A
, B
, F
, L
, R
>(self, predicate
: F
) -> (A
, B
)
1756 F
: Fn(Self::Item
) -> Either
<L
, R
>,
1757 A
: Default
+ Extend
<L
>,
1758 B
: Default
+ Extend
<R
>,
1760 let mut left
= A
::default();
1761 let mut right
= B
::default();
1764 match predicate(val
) {
1765 Either
::Left(v
) => left
.extend(Some(v
)),
1766 Either
::Right(v
) => right
.extend(Some(v
)),
1773 /// Return the minimum and maximum elements in the iterator.
1775 /// The return type `MinMaxResult` is an enum of three variants:
1777 /// - `NoElements` if the iterator is empty.
1778 /// - `OneElement(x)` if the iterator has exactly one element.
1779 /// - `MinMax(x, y)` is returned otherwise, where `x <= y`. Two
1780 /// values are equal if and only if there is more than one
1781 /// element in the iterator and all elements are equal.
1783 /// On an iterator of length `n`, `minmax` does `1.5 * n` comparisons,
1784 /// and so is faster than calling `min` and `max` separately which does
1785 /// `2 * n` comparisons.
1790 /// use itertools::Itertools;
1791 /// use itertools::MinMaxResult::{NoElements, OneElement, MinMax};
1793 /// let a: [i32; 0] = [];
1794 /// assert_eq!(a.iter().minmax(), NoElements);
1797 /// assert_eq!(a.iter().minmax(), OneElement(&1));
1799 /// let a = [1, 2, 3, 4, 5];
1800 /// assert_eq!(a.iter().minmax(), MinMax(&1, &5));
1802 /// let a = [1, 1, 1, 1];
1803 /// assert_eq!(a.iter().minmax(), MinMax(&1, &1));
1806 /// The elements can be floats but no particular result is guaranteed
1807 /// if an element is NaN.
1808 fn minmax(self) -> MinMaxResult
<Self::Item
>
1809 where Self: Sized
, Self::Item
: PartialOrd
1811 minmax
::minmax_impl(self, |_
| (), |x
, y
, _
, _
| x
< y
)
1814 /// Return the minimum and maximum element of an iterator, as determined by
1815 /// the specified function.
1817 /// The return value is a variant of `MinMaxResult` like for `minmax()`.
1819 /// For the minimum, the first minimal element is returned. For the maximum,
1820 /// the last maximal element wins. This matches the behavior of the standard
1821 /// `Iterator::min()` and `Iterator::max()` methods.
1823 /// The keys can be floats but no particular result is guaranteed
1824 /// if a key is NaN.
1825 fn minmax_by_key
<K
, F
>(self, key
: F
) -> MinMaxResult
<Self::Item
>
1826 where Self: Sized
, K
: PartialOrd
, F
: FnMut(&Self::Item
) -> K
1828 minmax
::minmax_impl(self, key
, |_
, _
, xk
, yk
| xk
< yk
)
1831 /// Return the minimum and maximum element of an iterator, as determined by
1832 /// the specified comparison function.
1834 /// The return value is a variant of `MinMaxResult` like for `minmax()`.
1836 /// For the minimum, the first minimal element is returned. For the maximum,
1837 /// the last maximal element wins. This matches the behavior of the standard
1838 /// `Iterator::min()` and `Iterator::max()` methods.
1839 fn minmax_by
<F
>(self, mut compare
: F
) -> MinMaxResult
<Self::Item
>
1840 where Self: Sized
, F
: FnMut(&Self::Item
, &Self::Item
) -> Ordering
1842 minmax
::minmax_impl(
1845 |x
, y
, _
, _
| Ordering
::Less
== compare(x
, y
)
1850 impl<T
: ?Sized
> Itertools
for T
where T
: Iterator { }
1852 /// Return `true` if both iterables produce equal sequences
1853 /// (elements pairwise equal and sequences of the same length),
1854 /// `false` otherwise.
1856 /// This is an `IntoIterator` enabled function that is similar to the standard
1857 /// library method `Iterator::eq`.
1860 /// assert!(itertools::equal(vec![1, 2, 3], 1..4));
1861 /// assert!(!itertools::equal(&[0, 0], &[0, 0, 0]));
1863 pub fn equal
<I
, J
>(a
: I
, b
: J
) -> bool
1864 where I
: IntoIterator
,
1866 I
::Item
: PartialEq
<J
::Item
>
1868 let mut ia
= a
.into_iter();
1869 let mut ib
= b
.into_iter();
1872 Some(x
) => match ib
.next() {
1873 Some(y
) => if x
!= y { return false; }
,
1874 None
=> return false,
1876 None
=> return ib
.next().is_none()
1881 /// Assert that two iterables produce equal sequences, with the same
1882 /// semantics as *equal(a, b)*.
1884 /// **Panics** on assertion failure with a message that shows the
1885 /// two iteration elements.
1888 /// assert_equal("exceed".split('c'), "excess".split('c'));
1889 /// // ^PANIC: panicked at 'Failed assertion Some("eed") == Some("ess") for iteration 1',
1891 pub fn assert_equal
<I
, J
>(a
: I
, b
: J
)
1892 where I
: IntoIterator
,
1894 I
::Item
: fmt
::Debug
+ PartialEq
<J
::Item
>,
1895 J
::Item
: fmt
::Debug
,
1897 let mut ia
= a
.into_iter();
1898 let mut ib
= b
.into_iter();
1901 match (ia
.next(), ib
.next()) {
1902 (None
, None
) => return,
1904 let equal
= match (&a
, &b
) {
1905 (&Some(ref a
), &Some(ref b
)) => a
== b
,
1908 assert
!(equal
, "Failed assertion {a:?} == {b:?} for iteration {i}",
1916 /// Partition a sequence using predicate `pred` so that elements
1917 /// that map to `true` are placed before elements which map to `false`.
1919 /// The order within the partitions is arbitrary.
1921 /// Return the index of the split point.
1924 /// use itertools::partition;
1926 /// # // use repeated numbers to not promise any ordering
1927 /// let mut data = [7, 1, 1, 7, 1, 1, 7];
1928 /// let split_index = partition(&mut data, |elt| *elt >= 3);
1930 /// assert_eq!(data, [7, 7, 7, 1, 1, 1, 1]);
1931 /// assert_eq!(split_index, 3);
1933 pub fn partition
<'a
, A
: 'a
, I
, F
>(iter
: I
, mut pred
: F
) -> usize
1934 where I
: IntoIterator
<Item
= &'a
mut A
>,
1935 I
::IntoIter
: DoubleEndedIterator
,
1936 F
: FnMut(&A
) -> bool
1938 let mut split_index
= 0;
1939 let mut iter
= iter
.into_iter();
1940 'main
: while let Some(front
) = iter
.next() {
1943 match iter
.next_back() {
1944 Some(back
) => if pred(back
) {
1945 std
::mem
::swap(front
, back
);
1948 None
=> break 'main
,
1957 /// An enum used for controlling the execution of `.fold_while()`.
1959 /// See [`.fold_while()`](trait.Itertools.html#method.fold_while) for more information.
1960 #[derive(Copy, Clone, Debug)]
1961 pub enum FoldWhile
<T
> {
1962 /// Continue folding with this value
1964 /// Fold is complete and will return this value
1968 impl<T
> FoldWhile
<T
> {
1969 /// Return the value in the continue or done.
1970 pub fn into_inner(self) -> T
{
1972 FoldWhile
::Continue(x
) | FoldWhile
::Done(x
) => x
,
1976 /// Return true if `self` is `Done`, false if it is `Continue`.
1977 pub fn is_done(&self) -> bool
{
1979 FoldWhile
::Continue(_
) => false,
1980 FoldWhile
::Done(_
) => true,