Skip to content

Instantly share code, notes, and snippets.

@ernestas-poskus
Forked from fero23/seq_ops.rs
Created December 9, 2016 23:07
Show Gist options
  • Save ernestas-poskus/977953cb261ed5a535387a9e36713208 to your computer and use it in GitHub Desktop.
Save ernestas-poskus/977953cb261ed5a535387a9e36713208 to your computer and use it in GitHub Desktop.
Intersection and difference operations for iterators in Rust
pub trait IterOps<T, I>: IntoIterator<Item = T>
where I: IntoIterator<Item = T>,
T: PartialEq {
fn intersect(self, other: I) -> Vec<T>;
fn difference(self, other: I) -> Vec<T>;
}
impl<T, I> IterOps<T, I> for I
where I: IntoIterator<Item = T>,
T: PartialEq
{
fn intersect(self, other: I) -> Vec<T> {
let mut common = Vec::new();
let mut v_other: Vec<_> = other.into_iter().collect();
for e1 in self.into_iter() {
if let Some(pos) = v_other.iter().position(|e2| e1 == *e2) {
common.push(e1);
v_other.remove(pos);
}
}
common
}
fn difference(self, other: I) -> Vec<T> {
let mut diff = Vec::new();
let mut v_other: Vec<_> = other.into_iter().collect();
for e1 in self.into_iter() {
if let Some(pos) = v_other.iter().position(|e2| e1 == *e2) {
v_other.remove(pos);
} else {
diff.push(e1);
}
}
diff.append(&mut v_other);
diff
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment