Skip to content

Commit d44084e

Browse files
thestingergraydon
authored andcommitted
implement set union
1 parent b8caba2 commit d44084e

File tree

1 file changed

+54
-3
lines changed

1 file changed

+54
-3
lines changed

src/libstd/treemap.rs

Lines changed: 54 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -301,15 +301,38 @@ impl <T: Ord> TreeSet<T> {
301301
}
302302

303303
/// Visit the values (in-order) representing the union
304-
pure fn union(&self, other: &TreeSet<T>, _f: fn(&T) -> bool) {
304+
pure fn union(&self, other: &TreeSet<T>, f: fn(&T) -> bool) {
305305
unsafe { // purity workaround
306306
let mut x = self.map.iter();
307307
let mut y = other.map.iter();
308308

309309
let mut a = x.next();
310310
let mut b = y.next();
311+
312+
while a.is_some() {
313+
if b.is_none() {
314+
while a.is_some() {
315+
let (a1, _) = a.unwrap();
316+
if !f(a1) { return }
317+
a = x.next();
318+
}
319+
}
320+
321+
let (a1, _) = a.unwrap();
322+
let (b1, _) = b.unwrap();
323+
324+
if b1 < a1 {
325+
if !f(b1) { return }
326+
b = y.next();
327+
} else {
328+
if !f(a1) { return }
329+
if !(a1 < b1) {
330+
b = y.next()
331+
}
332+
a = x.next();
333+
}
334+
}
311335
}
312-
fail ~"not yet implemented"
313336
}
314337
}
315338

@@ -866,7 +889,35 @@ mod test_set {
866889
let mut i = 0;
867890
let expected = [1, 5, 11];
868891
for a.difference(&b) |x| {
869-
io::println(fmt!("%?", x));
892+
assert *x == expected[i];
893+
i += 1
894+
}
895+
assert i == expected.len();
896+
}
897+
898+
#[test]
899+
fn test_union() {
900+
let mut a = TreeSet::new();
901+
let mut b = TreeSet::new();
902+
903+
assert a.insert(1);
904+
assert a.insert(3);
905+
assert a.insert(5);
906+
assert a.insert(9);
907+
assert a.insert(11);
908+
assert a.insert(16);
909+
assert a.insert(19);
910+
911+
assert b.insert(-2);
912+
assert b.insert(1);
913+
assert b.insert(5);
914+
assert b.insert(9);
915+
assert b.insert(13);
916+
assert b.insert(19);
917+
918+
let mut i = 0;
919+
let expected = [-2, 1, 3, 5, 9, 11, 13, 16, 19];
920+
for a.union(&b) |x| {
870921
assert *x == expected[i];
871922
i += 1
872923
}

0 commit comments

Comments
 (0)