@@ -243,20 +243,46 @@ impl <T: Ord> TreeSet<T> {
243
243
}
244
244
245
245
/// 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
+ }
249
276
}
250
277
251
278
/// Visit the values (in-order) representing the symmetric difference
252
279
pure fn symmetric_difference ( & self , _other : & TreeSet < T > ,
253
280
_f : fn ( & T ) -> bool ) {
254
- fail ~"not yet implemented" // TODO
281
+ fail ~"not yet implemented"
255
282
}
256
283
257
284
/// 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 ) {
260
286
// FIXME: this is a naive O(n*log(m)) implementation, could be O(n)
261
287
for self . each |x| {
262
288
if other. contains ( x) {
@@ -267,7 +293,7 @@ impl <T: Ord> TreeSet<T> {
267
293
268
294
/// Visit the values (in-order) representing the union
269
295
pure fn union ( & self , _other : & TreeSet < T > , _f : fn ( & T ) -> bool ) {
270
- fail ~"not yet implemented" // TODO
296
+ fail ~"not yet implemented"
271
297
}
272
298
}
273
299
@@ -806,4 +832,28 @@ mod test_set {
806
832
}
807
833
assert i == expected. len ( ) ;
808
834
}
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
+ }
809
859
}
0 commit comments