-
-
Save ernestas-poskus/977953cb261ed5a535387a9e36713208 to your computer and use it in GitHub Desktop.
Intersection and difference operations for iterators in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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