Skip to content

Commit 670748e

Browse files
thestingergraydon
authored andcommitted
implement set difference
1 parent 3b3ecc9 commit 670748e

File tree

1 file changed

+57
-7
lines changed

1 file changed

+57
-7
lines changed

src/libstd/treemap.rs

Lines changed: 57 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -243,20 +243,46 @@ impl <T: Ord> TreeSet<T> {
243243
}
244244

245245
/// Visit the values (in-order) representing the difference
246-
pure fn difference(&self, _other: &TreeSet<T>,
247-
_f: fn(&T) -> bool) {
248-
fail ~"not yet implemented" // TODO
246+
pure fn difference(&self, other: &TreeSet<T>, f: fn(&T) -> bool) {
247+
unsafe { // purity workaround
248+
let mut x = self.map.iter();
249+
let mut y = other.map.iter();
250+
251+
let mut a = x.next();
252+
let mut b = y.next();
253+
254+
while a.is_some() {
255+
if b.is_none() {
256+
while a.is_some() {
257+
let (a1, _) = a.unwrap();
258+
if !f(a1) { return }
259+
a = x.next();
260+
}
261+
return
262+
}
263+
264+
let (a1, _) = a.unwrap();
265+
let (b1, _) = b.unwrap();
266+
267+
if a1 < b1 {
268+
if !f(a1) { return }
269+
a = x.next();
270+
} else {
271+
if !(b1 < a1) { a = x.next() }
272+
b = y.next();
273+
}
274+
}
275+
}
249276
}
250277

251278
/// Visit the values (in-order) representing the symmetric difference
252279
pure fn symmetric_difference(&self, _other: &TreeSet<T>,
253280
_f: fn(&T) -> bool) {
254-
fail ~"not yet implemented" // TODO
281+
fail ~"not yet implemented"
255282
}
256283

257284
/// Visit the values (in-order) representing the intersection
258-
pure fn intersection(&self, other: &TreeSet<T>,
259-
f: fn(&T) -> bool) {
285+
pure fn intersection(&self, other: &TreeSet<T>, f: fn(&T) -> bool) {
260286
// FIXME: this is a naive O(n*log(m)) implementation, could be O(n)
261287
for self.each |x| {
262288
if other.contains(x) {
@@ -267,7 +293,7 @@ impl <T: Ord> TreeSet<T> {
267293

268294
/// Visit the values (in-order) representing the union
269295
pure fn union(&self, _other: &TreeSet<T>, _f: fn(&T) -> bool) {
270-
fail ~"not yet implemented" // TODO
296+
fail ~"not yet implemented"
271297
}
272298
}
273299

@@ -806,4 +832,28 @@ mod test_set {
806832
}
807833
assert i == expected.len();
808834
}
835+
836+
#[test]
837+
fn test_difference() {
838+
let mut a = TreeSet::new();
839+
let mut b = TreeSet::new();
840+
841+
a.insert(1);
842+
a.insert(3);
843+
a.insert(5);
844+
a.insert(9);
845+
a.insert(11);
846+
847+
b.insert(3);
848+
b.insert(9);
849+
850+
let mut i = 0;
851+
let expected = [1, 5, 11];
852+
for a.difference(&b) |x| {
853+
io::println(fmt!("%?", x));
854+
assert *x == expected[i];
855+
i += 1
856+
}
857+
assert i == expected.len();
858+
}
809859
}

0 commit comments

Comments
 (0)