Skip to content

Commit

Permalink
Implement unzip
Browse files Browse the repository at this point in the history
  • Loading branch information
sfackler committed Mar 10, 2019
1 parent 04620cd commit d269d1f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ pub trait FallibleIterator {
fn find_map<B, F>(&mut self, f: F) -> Result<Option<B>, Self::Error>
where
Self: Sized,
F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>
F: FnMut(Self::Item) -> Result<Option<B>, Self::Error>,
{
self.filter_map(f).next()
}
Expand Down Expand Up @@ -666,7 +666,7 @@ pub trait FallibleIterator {
Self: Sized,
F: FnMut(&Self::Item, &Self::Item) -> Result<Ordering, Self::Error>,
{
let mut min= match self.next()? {
let mut min = match self.next()? {
Some(v) => v,
None => return Ok(None),
};
Expand All @@ -690,6 +690,26 @@ pub trait FallibleIterator {
Rev(self)
}

/// Converts an iterator of pairs into a pair of containers.
#[inline]
fn unzip<A, B, FromA, FromB>(self) -> Result<(FromA, FromB), Self::Error>
where
Self: Sized + FallibleIterator<Item = (A, B)>,
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
{
let mut from_a = FromA::default();
let mut from_b = FromB::default();

self.for_each(|(a, b)| {
from_a.extend(Some(a));
from_b.extend(Some(b));
Ok(())
})?;

Ok((from_a, from_b))
}

/// Returns an iterator which clones all of its elements.
#[inline]
fn cloned<'a, T>(self) -> Cloned<Self>
Expand Down
8 changes: 8 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,11 @@ fn find_map() {
Ok(Some("hi"))
);
}

#[test]
fn unzip() {
let it = convert(vec![(0, 0), (1, -1), (2, -2), (3, -3)].into_iter().map(Ok::<_, ()>));
let (pos, neg): (Vec<i32>, Vec<i32>) = it.unzip().unwrap();
assert_eq!(pos, vec![0, 1, 2, 3]);
assert_eq!(neg, vec![0, -1, -2, -3]);
}

0 comments on commit d269d1f

Please sign in to comment.