Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement partition_result #511

Merged
merged 1 commit into from Jan 16, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/lib.rs
Expand Up @@ -2494,6 +2494,33 @@ pub trait Itertools : Iterator {
(left, right)
}

/// Partition a sequence of `Result`s into one list of all the `Ok` elements
/// and another list of all the `Err` elements.
///
/// ```
/// use itertools::Itertools;
///
/// let successes_and_failures = vec![Ok(1), Err(false), Err(true), Ok(2)];
///
/// let (successes, failures): (Vec<_>, Vec<_>) = successes_and_failures
/// .into_iter()
/// .partition_result();
///
/// assert_eq!(successes, [1, 2]);
/// assert_eq!(failures, [false, true]);
/// ```
fn partition_result<A, B, T, E>(self) -> (A, B)
where
Self: Iterator<Item = Result<T, E>> + Sized,
A: Default + Extend<T>,
B: Default + Extend<E>,
{
self.partition_map(|r| match r {
Ok(v) => Either::Left(v),
Err(v) => Either::Right(v),
})
}

/// Return a `HashMap` of keys mapped to `Vec`s of values. Keys and values
/// are taken from `(Key, Value)` tuple pairs yielded by the input iterator.
///
Expand Down