Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. pub trait IterOps<T, I>: IntoIterator<Item = T>
  2. where I: IntoIterator<Item = T>,
  3. T: PartialEq {
  4. fn intersect(self, other: I) -> Vec<T>;
  5. fn difference(self, other: I) -> Vec<T>;
  6. }
  7.  
  8. impl<T, I> IterOps<T, I> for I
  9. where I: IntoIterator<Item = T>,
  10. T: PartialEq
  11. {
  12. fn intersect(self, other: I) -> Vec<T> {
  13. let mut common = Vec::new();
  14. let mut v_other: Vec<_> = other.into_iter().collect();
  15.  
  16. for e1 in self.into_iter() {
  17. if let Some(pos) = v_other.iter().position(|e2| e1 == *e2) {
  18. common.push(e1);
  19. v_other.remove(pos);
  20. }
  21. }
  22.  
  23. common
  24. }
  25.  
  26. fn difference(self, other: I) -> Vec<T> {
  27. let mut diff = Vec::new();
  28. let mut v_other: Vec<_> = other.into_iter().collect();
  29.  
  30. for e1 in self.into_iter() {
  31. if let Some(pos) = v_other.iter().position(|e2| e1 == *e2) {
  32. v_other.remove(pos);
  33. } else {
  34. diff.push(e1);
  35. }
  36. }
  37.  
  38. diff.append(&mut v_other);
  39. diff
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement