Trait itertools::Itertools [] [src]

pub trait Itertools: Iterator {
    fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter> where J: IntoIterator<Item=Self::Item>, Self: Sized { ... }
    fn intersperse(self, element: Self::Item) -> Intersperse<Self> where Self: Sized, Self::Item: Clone { ... }
    fn zip_longest<J>(self, other: J) -> ZipLongest<Self, J::IntoIter> where J: IntoIterator, Self: Sized { ... }
    fn batching<B, F>(self, f: F) -> Batching<Self, F> where F: FnMut(&mut Self) -> Option<B>, Self: Sized { ... }
    fn group_by<K, F: FnMut(&Self::Item) -> K>(self, key: F) -> GroupBy<K, Self, F> where Self: Sized { ... }
    fn tee(self) -> (Tee<Self>, Tee<Self>) where Self: Sized, Self::Item: Clone { ... }
    fn slice<R>(self, range: R) -> ISlice<Self> where R: GenericRange, Self: Sized { ... }
    fn into_rc(self) -> RcIter<Self> where Self: Sized { ... }
    fn step(self, n: usize) -> Step<Self> where Self: Sized { ... }
    fn merge<J>(self, other: J) -> MergeAscend<Self, J::IntoIter> where Self: Sized, Self::Item: PartialOrd, J: IntoIterator<Item=Self::Item> { ... }
    fn merge_by<J, F>(self, other: J, cmp: F) -> Merge<Self, J::IntoIter, F> where Self: Sized, J: IntoIterator<Item=Self::Item>, F: FnMut(&Self::Item, &Self::Item) -> Ordering { ... }
    fn cartesian_product<J>(self, other: J) -> Product<Self, J::IntoIter> where Self: Sized, Self::Item: Clone, J: IntoIterator, J::IntoIter: Clone { ... }
    fn multipeek(self) -> MultiPeek<Self> where Self: Sized { ... }
    fn coalesce<F>(self, f: F) -> Coalesce<Self, F> where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Result<Self::Item, (Self::Item, Self::Item)> { ... }
    fn dedup(self) -> CoalesceFn<Self> where Self: Sized, Self::Item: PartialEq { ... }
    fn mend_slices(self) -> CoalesceFn<Self> where Self: Sized, Self::Item: MendSlice { ... }
    fn take_while_ref<'a, F>(&'a mut self, f: F) -> TakeWhileRef<'a, Self, F> where Self: Clone, F: FnMut(&Self::Item) -> bool { ... }
    fn map_fn<B>(self, f: fn(Self::Item) -> B) -> MapFn<Self, B> where Self: Sized { ... }
    fn fn_map<B>(self, map: fn(Self::Item) -> B) -> FnMap<B, Self> where Self: Sized { ... }
    fn find_position<P>(&mut self, pred: P) -> Option<(usize, Self::Item)> where P: FnMut(&Self::Item) -> bool { ... }
    fn dropn(&mut self, n: usize) -> usize { ... }
    fn dropping(self, n: usize) -> Self where Self: Sized { ... }
    fn dropping_back(self, n: usize) -> Self where Self: Sized, Self: DoubleEndedIterator { ... }
    fn foreach<F>(&mut self, f: F) where F: FnMut(Self::Item) { ... }
    fn collect_vec(self) -> Vec<Self::Item> where Self: Sized { ... }
    fn set_from<'a, A: 'a, J>(&mut self, from: J) -> usize where Self: Iterator<Item=&'a mut A>, J: IntoIterator<Item=A> { ... }
    fn join(&mut self, sep: &str) -> String where Self::Item: Display { ... }
    fn fold_results<A, E, B, F>(&mut self, start: B, f: F) -> Result<B, E> where Self: Iterator<Item=Result<A, E>>, F: FnMut(B, A) -> B { ... }
    fn fold1<F>(&mut self, f: F) -> Option<Self::Item> where F: FnMut(Self::Item, Self::Item) -> Self::Item { ... }
    fn is_empty_hint(&self) -> Option<bool> { ... }
}

The trait Itertools: extra iterator adaptors and methods for iterators.

This trait defines a number of methods. They are divided into two groups:

  • Adaptors take an interator and parameter as input, and return a new iterator value. These are listed first in the trait. An example of an adaptor is .interleave()

  • Regular methods are those that don't return iterators and instead return a regular value of some other kind. .find_position() is an example and the first regular method in the list.

Provided Methods

fn interleave<J>(self, other: J) -> Interleave<Self, J::IntoIter> where J: IntoIterator<Item=Self::Item>, Self: Sized

Alternate elements from two iterators until both run out.

Iterator element type is Self::Item.

This iterator is fused.

Example

use itertools::Itertools;

let it = (0..3).interleave(vec![7, 7]);
assert!(itertools::equal(it, vec![0, 7, 1, 7, 2]));

fn intersperse(self, element: Self::Item) -> Intersperse<Self> where Self: Sized, Self::Item: Clone

An iterator adaptor to insert a particular value between each element of the adapted iterator.

Iterator element type is Self::Item.

This iterator is fused.

fn zip_longest<J>(self, other: J) -> ZipLongest<Self, J::IntoIter> where J: IntoIterator, Self: Sized

Create an iterator which iterates over both this and the specified iterator simultaneously, yielding pairs of two optional elements.

This iterator is fused.

When both iterators return None, all further invocations of .next() will return None.

Example

use itertools::EitherOrBoth::{Both, Right};
use itertools::Itertools;
let it = (0..1).zip_longest(1..3);
assert!(itertools::equal(it, vec![Both(0, 1), Right(2)]));

Iterator element type is EitherOrBoth<Self::Item, J::Item>.

fn batching<B, F>(self, f: F) -> Batching<Self, F> where F: FnMut(&mut Self) -> Option<B>, Self: Sized

A “meta iterator adaptor”. Its closure recives a reference to the iterator and may pick off as many elements as it likes, to produce the next iterator element.

Iterator element type is B.

Example

use itertools::Itertools;

// An adaptor that gathers elements up in pairs
let pit = (0..4).batching(|mut it| {
           match it.next() {
               None => None,
               Some(x) => match it.next() {
                   None => None,
                   Some(y) => Some((x, y)),
               }
           }
       });

assert!(itertools::equal(pit, vec![(0, 1), (2, 3)]));

fn group_by<K, F: FnMut(&Self::Item) -> K>(self, key: F) -> GroupBy<K, Self, F> where Self: Sized

Group iterator elements. Consecutive elements that map to the same key (“runs”), are returned as the iterator elements of GroupBy.

Iterator element type is (K, Vec<Self::Item>)

fn tee(self) -> (Tee<Self>, Tee<Self>) where Self: Sized, Self::Item: Clone

Split into an iterator pair that both yield all elements from the original iterator.

Note: If the iterator is clonable, prefer using that instead of using this method. It is likely to be more efficient.

Iterator element type is Self::Item.

Example

use itertools::Itertools;
let xs = vec![0, 1, 2, 3];

let (mut t1, mut t2) = xs.into_iter().tee();
assert_eq!(t1.next(), Some(0));
assert_eq!(t1.next(), Some(1));
assert_eq!(t2.next(), Some(0));
assert_eq!(t1.next(), Some(2));
assert_eq!(t1.next(), Some(3));
assert_eq!(t1.next(), None);
assert_eq!(t2.next(), Some(1));

fn slice<R>(self, range: R) -> ISlice<Self> where R: GenericRange, Self: Sized

Return a sliced iterator.

Note: slicing an iterator is not constant time, and much less efficient than slicing for example a vector.

Iterator element type is Self::Item.

Example

use std::iter::repeat;
use itertools::Itertools;

let it = repeat('a').slice(..3);
assert_eq!(it.count(), 3);

fn into_rc(self) -> RcIter<Self> where Self: Sized

Return an iterator inside a Rc<RefCell<_>> wrapper.

The returned RcIter can be cloned, and each clone will refer back to the same original iterator.

RcIter allows doing interesting things like using .zip() on an iterator with itself, at the cost of runtime borrow checking. (If it is not obvious: this has a performance penalty.)

Iterator element type is Self::Item.

Example

use itertools::Itertools;

let mut rit = (0..9).into_rc();
let mut z = rit.clone().zip(rit.clone());
assert_eq!(z.next(), Some((0, 1)));
assert_eq!(z.next(), Some((2, 3)));
assert_eq!(z.next(), Some((4, 5)));
assert_eq!(rit.next(), Some(6));
assert_eq!(z.next(), Some((7, 8)));
assert_eq!(z.next(), None);

Panics in iterator methods if a borrow error is encountered, but it can only happen if the RcIter is reentered in for example .next(), i.e. if it somehow participates in an “iterator knot” where it is an adaptor of itself.

fn step(self, n: usize) -> Step<Self> where Self: Sized

Return an iterator adaptor that steps n elements in the base iterator for each iteration.

The iterator steps by yielding the next element from the base iterator, then skipping forward n - 1 elements.

Iterator element type is Self::Item.

Panics if the step is 0.

Example

use itertools::Itertools;

let it = (0..8).step(3);
assert!(itertools::equal(it, vec![0, 3, 6]));

fn merge<J>(self, other: J) -> MergeAscend<Self, J::IntoIter> where Self: Sized, Self::Item: PartialOrd, J: IntoIterator<Item=Self::Item>

Return an iterator adaptor that merges the two base iterators in ascending order. If both base iterators are sorted (ascending), the result is sorted.

Iterator element type is Self::Item.

Example

use itertools::Itertools;

let a = (0..11).step(3);
let b = (0..11).step(5);
let it = a.merge(b);
assert!(itertools::equal(it, vec![0, 0, 3, 5, 6, 9, 10]));

fn merge_by<J, F>(self, other: J, cmp: F) -> Merge<Self, J::IntoIter, F> where Self: Sized, J: IntoIterator<Item=Self::Item>, F: FnMut(&Self::Item, &Self::Item) -> Ordering

Return an iterator adaptor that merges the two base iterators in order. This is much like .merge() but allows for a custom ordering.

This can be especially useful for sequences of tuples.

Iterator element type is Self::Item.

Example

use itertools::Itertools;

let a = (0..).zip("bc".chars());
let b = (0..).zip("ad".chars());
let it = a.merge_by(b, |x, y| x.1.cmp(&y.1));
assert!(itertools::equal(it, vec![(0, 'a'), (0, 'b'), (1, 'c'), (1, 'd')]));

fn cartesian_product<J>(self, other: J) -> Product<Self, J::IntoIter> where Self: Sized, Self::Item: Clone, J: IntoIterator, J::IntoIter: Clone

Return an iterator adaptor that iterates over the cartesian product of the element sets of two iterators self and J.

Iterator element type is (Self::Item, J::Item).

use itertools::Itertools;

let it = (0..2).cartesian_product("αβ".chars());
assert!(itertools::equal(it, vec![(0, 'α'), (0, 'β'), (1, 'α'), (1, 'β')]));

fn multipeek(self) -> MultiPeek<Self> where Self: Sized

Return an iterator adapter that allows peeking multiple values.

After a call to .next() the peeking cursor is reset.

Example

use itertools::Itertools;

let nums = vec![1u8,2,3,4,5];
let mut peekable = nums.into_iter().multipeek();
assert_eq!(peekable.peek(), Some(&1));
assert_eq!(peekable.peek(), Some(&2));
assert_eq!(peekable.peek(), Some(&3));
assert_eq!(peekable.next(), Some(1));
assert_eq!(peekable.peek(), Some(&2));

fn coalesce<F>(self, f: F) -> Coalesce<Self, F> where Self: Sized, F: FnMut(Self::Item, Self::Item) -> Result<Self::Item, (Self::Item, Self::Item)>

Return an iterator adaptor that uses the passed-in closure to optionally merge together consecutive elements. For each pair the closure is passed the latest two elements, x, y and may return either Ok(z) to merge the two values or Err((x, y)) to indicate they can't be merged.

.dedup() and .mend_slices() are specializations of the coalesce adaptor.

Iterator element type is Self::Item.

This iterator is fused.

Example

use itertools::Itertools;

// sum same-sign runs together
let data = vec![-1., -2., -3., 3., 1., 0., -1.];
assert!(itertools::equal(data.into_iter().coalesce(|x, y|
        if (x >= 0.) == (y >= 0.) {
            Ok(x + y)
        } else {
            Err((x, y))
        }),
        vec![-6., 4., -1.]));

fn dedup(self) -> CoalesceFn<Self> where Self: Sized, Self::Item: PartialEq

Remove duplicates from sections of consecutive identical elements. If the iterator is sorted, all elements will be unique.

Iterator element type is Self::Item.

This iterator is fused.

Example

use itertools::Itertools;

let data = vec![1., 1., 2., 3., 3., 2., 2.];
assert!(itertools::equal(data.into_iter().dedup(),
                         vec![1., 2., 3., 2.]));

fn mend_slices(self) -> CoalesceFn<Self> where Self: Sized, Self::Item: MendSlice

Return an iterator adaptor that joins together adjacent slices if possible.

Only implemented for iterators with slice or string slice elements. Only slices that are contiguous together can be joined.

Example

use itertools::Itertools;

let text = String::from("let there be text");
let excerpts = vec![&text[0..4], &text[4..9], &text[10..12], &text[12..]];

assert!(itertools::equal(excerpts.into_iter().mend_slices(),
                         vec!["let there", "be text"]));

fn take_while_ref<'a, F>(&'a mut self, f: F) -> TakeWhileRef<'a, Self, F> where Self: Clone, F: FnMut(&Self::Item) -> bool

Return an iterator adaptor that borrows from a Clone-able iterator to only pick off elements while the predicate f returns true.

It uses the Clone trait to restore the original iterator so that the last and rejected element is still available when TakeWhileRef is done.

Example

use itertools::Itertools;

let mut alphanumerics = "abcdef012345".chars();

let alphas = alphanumerics.take_while_ref(|c| c.is_alphabetic())
                          .collect::<String>();
assert_eq!(alphas, "abcdef");
assert_eq!(alphanumerics.next(), Some('0'));

fn map_fn<B>(self, f: fn(Self::Item) -> B) -> MapFn<Self, B> where Self: Sized

Like regular .map(), specialized to using a simple function pointer instead, so that the resulting Map iterator value can be cloned.

Iterator element type is B.

fn fn_map<B>(self, map: fn(Self::Item) -> B) -> FnMap<B, Self> where Self: Sized

Deprecated: Use .map_fn() instead.

fn find_position<P>(&mut self, pred: P) -> Option<(usize, Self::Item)> where P: FnMut(&Self::Item) -> bool

Find the position and value of the first element satisfying a predicate.

fn dropn(&mut self, n: usize) -> usize

Consume the first n elements of the iterator eagerly.

Return actual number of elements consumed, until done or reaching the end.

fn dropping(self, n: usize) -> Self where Self: Sized

Consume the first n elements from the iterator eagerly, and return the same iterator again.

It works similarly to .skip(n) except it is eager and preserves the iterator type.

fn dropping_back(self, n: usize) -> Self where Self: Sized, Self: DoubleEndedIterator

Consume the last n elements from the iterator eagerly, and return the same iterator again.

This is only possible on double ended iterators. n may be larger than the number of elements.

Note: This method is eager, dropping the back elements immediately and preserves the iterator type.

Example

use itertools::Itertools;

let init = vec![0, 3, 6, 9].into_iter().dropping_back(1);
assert!(itertools::equal(init, vec![0, 3, 6]));

fn foreach<F>(&mut self, f: F) where F: FnMut(Self::Item)

Run the closure f eagerly on each element of the iterator.

Consumes the iterator until its end.

Example

use std::sync::mpsc::channel;
use itertools::Itertools;

let (tx, rx) = channel();

// use .foreach() to apply a function to each value -- sending it
(0..5).map(|x| x * 2 + 1).foreach(|x| { tx.send(x).unwrap(); } );

drop(tx);

assert!(itertools::equal(rx.iter(), vec![1, 3, 5, 7, 9]));

fn collect_vec(self) -> Vec<Self::Item> where Self: Sized

.collect_vec() is simply a type specialization of .collect(), for convenience.

fn set_from<'a, A: 'a, J>(&mut self, from: J) -> usize where Self: Iterator<Item=&'a mut A>, J: IntoIterator<Item=A>

Assign to each reference in self from the from iterator, stopping at the shortest of the two iterators.

The from iterator is queried for its next element before the self iterator, and if either is exhausted the method is done.

Return the number of elements written.

Example

use itertools::Itertools;

let mut xs = [0; 4];
xs.iter_mut().set_from(1..);
assert_eq!(xs, [1, 2, 3, 4]);

fn join(&mut self, sep: &str) -> String where Self::Item: Display

Combine all iterator elements into one String, seperated by sep.

Use the Display implementation of each element.

Example

use itertools::Itertools;

assert_eq!(["a", "b", "c"].iter().join(", "), "a, b, c");
assert_eq!([1, 2, 3].iter().join(", "), "1, 2, 3");

fn fold_results<A, E, B, F>(&mut self, start: B, f: F) -> Result<B, E> where Self: Iterator<Item=Result<A, E>>, F: FnMut(B, A) -> B

Fold Result values from an iterator.

Only Ok values are folded. If no error is encountered, the folded value is returned inside Ok. Otherwise, the operation terminates and returns the first Err value it encounters. No iterator elements are consumed after the first error.

The first accumulator value is the start parameter. Each iteration passes the accumulator value and the next value inside Ok to the fold function f and its return value becomes the new accumulator value.

For example the sequence Ok(1), Ok(2), Ok(3) will result in a computation like this:

let mut accum = start;
accum = f(accum, 1);
accum = f(accum, 2);
accum = f(accum, 3);

With a start value of 0 and an addition as folding function, this effetively results in ((0 + 1) + 2) + 3

Example

use std::ops::Add;
use itertools::Itertools;

let values = [1, 2, -2, -1, 2, 1];
assert_eq!(
    values.iter()
        .map(Ok::<_, ()>)
        .fold_results(0, Add::add),
    Ok(3)
);
assert!(
    values.iter()
        .map(|&x| if x >= 0 { Ok(x) } else { Err("Negative number") })
        .fold_results(0, Add::add)
        .is_err()
);

fn fold1<F>(&mut self, f: F) -> Option<Self::Item> where F: FnMut(Self::Item, Self::Item) -> Self::Item

Accumulator of the elements in the iterator.

Like .fold(), without a base case. If the iterator is empty, return None. With just one element, return it. Otherwise elements are accumulated in sequence using the closure f.

Example

use itertools::Itertools;

assert_eq!((0..10).fold1(|x, y| x + y).unwrap_or(0), 45);
assert_eq!((0..0).fold1(|x, y| x * y), None);

fn is_empty_hint(&self) -> Option<bool>

Tell if the iterator is empty or not according to its size hint. Return None if the size hint does not tell, or return a Some value with the emptiness if it's possible to tell.

Example

use itertools::Itertools;

assert_eq!((1..1).is_empty_hint(), Some(true));
assert_eq!([1, 2, 3].iter().is_empty_hint(), Some(false));
assert_eq!((0..10).filter(|&x| x > 0).is_empty_hint(), None);

Implementors