Skip to content

Instantly share code, notes, and snippets.

@fero23
Last active January 10, 2023 10:05
Show Gist options
  • Save fero23/9d21828fd879ff0f8a8bde6abd486366 to your computer and use it in GitHub Desktop.
Save fero23/9d21828fd879ff0f8a8bde6abd486366 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