undo breakage caused by -Wall cleaning
[packages/containers.git] / Data / Set.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module : Data.Set
4 -- Copyright : (c) Daan Leijen 2002
5 -- License : BSD-style
6 -- Maintainer : libraries@haskell.org
7 -- Stability : provisional
8 -- Portability : portable
9 --
10 -- An efficient implementation of sets.
11 --
12 -- Since many function names (but not the type name) clash with
13 -- "Prelude" names, this module is usually imported @qualified@, e.g.
14 --
15 -- > import Data.Set (Set)
16 -- > import qualified Data.Set as Set
17 --
18 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
19 -- trees of /bounded balance/) as described by:
20 --
21 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
22 -- Journal of Functional Programming 3(4):553-562, October 1993,
23 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
24 --
25 -- * J. Nievergelt and E.M. Reingold,
26 -- \"/Binary search trees of bounded balance/\",
27 -- SIAM journal of computing 2(1), March 1973.
28 --
29 -- Note that the implementation is /left-biased/ -- the elements of a
30 -- first argument are always preferred to the second, for example in
31 -- 'union' or 'insert'. Of course, left-biasing can only be observed
32 -- when equality is an equivalence relation instead of structural
33 -- equality.
34 -----------------------------------------------------------------------------
35
36 module Data.Set (
37 -- * Set type
38 Set -- instance Eq,Ord,Show,Read,Data,Typeable
39
40 -- * Operators
41 , (\\)
42
43 -- * Query
44 , null
45 , size
46 , member
47 , notMember
48 , isSubsetOf
49 , isProperSubsetOf
50
51 -- * Construction
52 , empty
53 , singleton
54 , insert
55 , delete
56
57 -- * Combine
58 , union, unions
59 , difference
60 , intersection
61
62 -- * Filter
63 , filter
64 , partition
65 , split
66 , splitMember
67
68 -- * Map
69 , map
70 , mapMonotonic
71
72 -- * Fold
73 , fold
74
75 -- * Min\/Max
76 , findMin
77 , findMax
78 , deleteMin
79 , deleteMax
80 , deleteFindMin
81 , deleteFindMax
82 , maxView
83 , minView
84
85 -- * Conversion
86
87 -- ** List
88 , elems
89 , toList
90 , fromList
91
92 -- ** Ordered list
93 , toAscList
94 , fromAscList
95 , fromDistinctAscList
96
97 -- * Debugging
98 , showTree
99 , showTreeWith
100 , valid
101 ) where
102
103 import Prelude hiding (filter,foldr,null,map)
104 import qualified Data.List as List
105 import Data.Monoid (Monoid(..))
106 import Data.Foldable (Foldable(foldMap))
107 import Data.Typeable
108
109 {-
110 -- just for testing
111 import QuickCheck
112 import List (nub,sort)
113 import qualified List
114 -}
115
116 #if __GLASGOW_HASKELL__
117 import Text.Read
118 import Data.Generics.Basics
119 import Data.Generics.Instances ()
120 #endif
121
122 {--------------------------------------------------------------------
123 Operators
124 --------------------------------------------------------------------}
125 infixl 9 \\ --
126
127 -- | /O(n+m)/. See 'difference'.
128 (\\) :: Ord a => Set a -> Set a -> Set a
129 m1 \\ m2 = difference m1 m2
130
131 {--------------------------------------------------------------------
132 Sets are size balanced trees
133 --------------------------------------------------------------------}
134 -- | A set of values @a@.
135 data Set a = Tip
136 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
137
138 type Size = Int
139
140 instance Ord a => Monoid (Set a) where
141 mempty = empty
142 mappend = union
143 mconcat = unions
144
145 instance Foldable Set where
146 foldMap _ Tip = mempty
147 foldMap f (Bin _s k l r) = foldMap f l `mappend` f k `mappend` foldMap f r
148
149 #if __GLASGOW_HASKELL__
150
151 {--------------------------------------------------------------------
152 A Data instance
153 --------------------------------------------------------------------}
154
155 -- This instance preserves data abstraction at the cost of inefficiency.
156 -- We omit reflection services for the sake of data abstraction.
157
158 instance (Data a, Ord a) => Data (Set a) where
159 gfoldl f z set = z fromList `f` (toList set)
160 toConstr _ = error "toConstr"
161 gunfold _ _ = error "gunfold"
162 dataTypeOf _ = mkNorepType "Data.Set.Set"
163 dataCast1 f = gcast1 f
164
165 #endif
166
167 {--------------------------------------------------------------------
168 Query
169 --------------------------------------------------------------------}
170 -- | /O(1)/. Is this the empty set?
171 null :: Set a -> Bool
172 null t
173 = case t of
174 Tip -> True
175 Bin {} -> False
176
177 -- | /O(1)/. The number of elements in the set.
178 size :: Set a -> Int
179 size t
180 = case t of
181 Tip -> 0
182 Bin sz _ _ _ -> sz
183
184 -- | /O(log n)/. Is the element in the set?
185 member :: Ord a => a -> Set a -> Bool
186 member x t
187 = case t of
188 Tip -> False
189 Bin _ y l r
190 -> case compare x y of
191 LT -> member x l
192 GT -> member x r
193 EQ -> True
194
195 -- | /O(log n)/. Is the element not in the set?
196 notMember :: Ord a => a -> Set a -> Bool
197 notMember x t = not $ member x t
198
199 {--------------------------------------------------------------------
200 Construction
201 --------------------------------------------------------------------}
202 -- | /O(1)/. The empty set.
203 empty :: Set a
204 empty
205 = Tip
206
207 -- | /O(1)/. Create a singleton set.
208 singleton :: a -> Set a
209 singleton x
210 = Bin 1 x Tip Tip
211
212 {--------------------------------------------------------------------
213 Insertion, Deletion
214 --------------------------------------------------------------------}
215 -- | /O(log n)/. Insert an element in a set.
216 -- If the set already contains an element equal to the given value,
217 -- it is replaced with the new value.
218 insert :: Ord a => a -> Set a -> Set a
219 insert x t
220 = case t of
221 Tip -> singleton x
222 Bin sz y l r
223 -> case compare x y of
224 LT -> balance y (insert x l) r
225 GT -> balance y l (insert x r)
226 EQ -> Bin sz x l r
227
228
229 -- | /O(log n)/. Delete an element from a set.
230 delete :: Ord a => a -> Set a -> Set a
231 delete x t
232 = case t of
233 Tip -> Tip
234 Bin _ y l r
235 -> case compare x y of
236 LT -> balance y (delete x l) r
237 GT -> balance y l (delete x r)
238 EQ -> glue l r
239
240 {--------------------------------------------------------------------
241 Subset
242 --------------------------------------------------------------------}
243 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
244 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
245 isProperSubsetOf s1 s2
246 = (size s1 < size s2) && (isSubsetOf s1 s2)
247
248
249 -- | /O(n+m)/. Is this a subset?
250 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
251 isSubsetOf :: Ord a => Set a -> Set a -> Bool
252 isSubsetOf t1 t2
253 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
254
255 isSubsetOfX :: Ord a => Set a -> Set a -> Bool
256 isSubsetOfX Tip _ = True
257 isSubsetOfX _ Tip = False
258 isSubsetOfX (Bin _ x l r) t
259 = found && isSubsetOfX l lt && isSubsetOfX r gt
260 where
261 (lt,found,gt) = splitMember x t
262
263
264 {--------------------------------------------------------------------
265 Minimal, Maximal
266 --------------------------------------------------------------------}
267 -- | /O(log n)/. The minimal element of a set.
268 findMin :: Set a -> a
269 findMin (Bin _ x Tip _) = x
270 findMin (Bin _ _ l _) = findMin l
271 findMin Tip = error "Set.findMin: empty set has no minimal element"
272
273 -- | /O(log n)/. The maximal element of a set.
274 findMax :: Set a -> a
275 findMax (Bin _ x _ Tip) = x
276 findMax (Bin _ _ _ r) = findMax r
277 findMax Tip = error "Set.findMax: empty set has no maximal element"
278
279 -- | /O(log n)/. Delete the minimal element.
280 deleteMin :: Set a -> Set a
281 deleteMin (Bin _ _ Tip r) = r
282 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
283 deleteMin Tip = Tip
284
285 -- | /O(log n)/. Delete the maximal element.
286 deleteMax :: Set a -> Set a
287 deleteMax (Bin _ _ l Tip) = l
288 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
289 deleteMax Tip = Tip
290
291
292 {--------------------------------------------------------------------
293 Union.
294 --------------------------------------------------------------------}
295 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
296 unions :: Ord a => [Set a] -> Set a
297 unions ts
298 = foldlStrict union empty ts
299
300
301 -- | /O(n+m)/. The union of two sets, preferring the first set when
302 -- equal elements are encountered.
303 -- The implementation uses the efficient /hedge-union/ algorithm.
304 -- Hedge-union is more efficient on (bigset `union` smallset).
305 union :: Ord a => Set a -> Set a -> Set a
306 union Tip t2 = t2
307 union t1 Tip = t1
308 union t1 t2 = hedgeUnion (const LT) (const GT) t1 t2
309
310 hedgeUnion :: Ord a
311 => (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a -> Set a
312 hedgeUnion _ _ t1 Tip
313 = t1
314 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
315 = join x (filterGt cmplo l) (filterLt cmphi r)
316 hedgeUnion cmplo cmphi (Bin _ x l r) t2
317 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
318 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
319 where
320 cmpx y = compare x y
321
322 {--------------------------------------------------------------------
323 Difference
324 --------------------------------------------------------------------}
325 -- | /O(n+m)/. Difference of two sets.
326 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
327 difference :: Ord a => Set a -> Set a -> Set a
328 difference Tip _ = Tip
329 difference t1 Tip = t1
330 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
331
332 hedgeDiff :: Ord a
333 => (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a -> Set a
334 hedgeDiff _ _ Tip _
335 = Tip
336 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
337 = join x (filterGt cmplo l) (filterLt cmphi r)
338 hedgeDiff cmplo cmphi t (Bin _ x l r)
339 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
340 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
341 where
342 cmpx y = compare x y
343
344 {--------------------------------------------------------------------
345 Intersection
346 --------------------------------------------------------------------}
347 -- | /O(n+m)/. The intersection of two sets.
348 -- Elements of the result come from the first set, so for example
349 --
350 -- > import qualified Data.Set as S
351 -- > data AB = A | B deriving Show
352 -- > instance Ord AB where compare _ _ = EQ
353 -- > instance Eq AB where _ == _ = True
354 -- > main = print (S.singleton A `S.intersection` S.singleton B,
355 -- > S.singleton B `S.intersection` S.singleton A)
356 --
357 -- prints @(fromList [A],fromList [B])@.
358 intersection :: Ord a => Set a -> Set a -> Set a
359 intersection Tip _ = Tip
360 intersection _ Tip = Tip
361 intersection t1@(Bin s1 x1 l1 r1) t2@(Bin s2 x2 l2 r2) =
362 if s1 >= s2 then
363 let (lt,found,gt) = splitLookup x2 t1
364 tl = intersection lt l2
365 tr = intersection gt r2
366 in case found of
367 Just x -> join x tl tr
368 Nothing -> merge tl tr
369 else let (lt,found,gt) = splitMember x1 t2
370 tl = intersection l1 lt
371 tr = intersection r1 gt
372 in if found then join x1 tl tr
373 else merge tl tr
374
375 {--------------------------------------------------------------------
376 Filter and partition
377 --------------------------------------------------------------------}
378 -- | /O(n)/. Filter all elements that satisfy the predicate.
379 filter :: Ord a => (a -> Bool) -> Set a -> Set a
380 filter _ Tip = Tip
381 filter p (Bin _ x l r)
382 | p x = join x (filter p l) (filter p r)
383 | otherwise = merge (filter p l) (filter p r)
384
385 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
386 -- the predicate and one with all elements that don't satisfy the predicate.
387 -- See also 'split'.
388 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
389 partition _ Tip = (Tip,Tip)
390 partition p (Bin _ x l r)
391 | p x = (join x l1 r1,merge l2 r2)
392 | otherwise = (merge l1 r1,join x l2 r2)
393 where
394 (l1,l2) = partition p l
395 (r1,r2) = partition p r
396
397 {----------------------------------------------------------------------
398 Map
399 ----------------------------------------------------------------------}
400
401 -- | /O(n*log n)/.
402 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
403 --
404 -- It's worth noting that the size of the result may be smaller if,
405 -- for some @(x,y)@, @x \/= y && f x == f y@
406
407 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
408 map f = fromList . List.map f . toList
409
410 -- | /O(n)/. The
411 --
412 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
413 -- /The precondition is not checked./
414 -- Semi-formally, we have:
415 --
416 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
417 -- > ==> mapMonotonic f s == map f s
418 -- > where ls = toList s
419
420 mapMonotonic :: (a->b) -> Set a -> Set b
421 mapMonotonic _ Tip = Tip
422 mapMonotonic f (Bin sz x l r) =
423 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
424
425
426 {--------------------------------------------------------------------
427 Fold
428 --------------------------------------------------------------------}
429 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
430 fold :: (a -> b -> b) -> b -> Set a -> b
431 fold f z s
432 = foldr f z s
433
434 -- | /O(n)/. Post-order fold.
435 foldr :: (a -> b -> b) -> b -> Set a -> b
436 foldr _ z Tip = z
437 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
438
439 {--------------------------------------------------------------------
440 List variations
441 --------------------------------------------------------------------}
442 -- | /O(n)/. The elements of a set.
443 elems :: Set a -> [a]
444 elems s
445 = toList s
446
447 {--------------------------------------------------------------------
448 Lists
449 --------------------------------------------------------------------}
450 -- | /O(n)/. Convert the set to a list of elements.
451 toList :: Set a -> [a]
452 toList s
453 = toAscList s
454
455 -- | /O(n)/. Convert the set to an ascending list of elements.
456 toAscList :: Set a -> [a]
457 toAscList t
458 = foldr (:) [] t
459
460
461 -- | /O(n*log n)/. Create a set from a list of elements.
462 fromList :: Ord a => [a] -> Set a
463 fromList xs
464 = foldlStrict ins empty xs
465 where
466 ins t x = insert x t
467
468 {--------------------------------------------------------------------
469 Building trees from ascending/descending lists can be done in linear time.
470
471 Note that if [xs] is ascending that:
472 fromAscList xs == fromList xs
473 --------------------------------------------------------------------}
474 -- | /O(n)/. Build a set from an ascending list in linear time.
475 -- /The precondition (input list is ascending) is not checked./
476 fromAscList :: Eq a => [a] -> Set a
477 fromAscList xs
478 = fromDistinctAscList (combineEq xs)
479 where
480 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
481 combineEq xs'
482 = case xs' of
483 [] -> []
484 [x] -> [x]
485 (x:xx) -> combineEq' x xx
486
487 combineEq' z [] = [z]
488 combineEq' z (x:xs')
489 | z==x = combineEq' z xs'
490 | otherwise = z:combineEq' x xs'
491
492
493 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
494 -- /The precondition (input list is strictly ascending) is not checked./
495 fromDistinctAscList :: [a] -> Set a
496 fromDistinctAscList xs
497 = build const (length xs) xs
498 where
499 -- 1) use continutations so that we use heap space instead of stack space.
500 -- 2) special case for n==5 to build bushier trees.
501 build c 0 xs' = c Tip xs'
502 build c 5 xs' = case xs' of
503 (x1:x2:x3:x4:x5:xx)
504 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
505 _ -> error "fromDistinctAscList build 5"
506 build c n xs' = seq nr $ build (buildR nr c) nl xs'
507 where
508 nl = n `div` 2
509 nr = n - nl - 1
510
511 buildR n c l (x:ys) = build (buildB l x c) n ys
512 buildR _ _ _ [] = error "fromDistinctAscList buildR []"
513 buildB l x c r zs = c (bin x l r) zs
514
515 {--------------------------------------------------------------------
516 Eq converts the set to a list. In a lazy setting, this
517 actually seems one of the faster methods to compare two trees
518 and it is certainly the simplest :-)
519 --------------------------------------------------------------------}
520 instance Eq a => Eq (Set a) where
521 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
522
523 {--------------------------------------------------------------------
524 Ord
525 --------------------------------------------------------------------}
526
527 instance Ord a => Ord (Set a) where
528 compare s1 s2 = compare (toAscList s1) (toAscList s2)
529
530 {--------------------------------------------------------------------
531 Show
532 --------------------------------------------------------------------}
533 instance Show a => Show (Set a) where
534 showsPrec p xs = showParen (p > 10) $
535 showString "fromList " . shows (toList xs)
536
537 {-
538 XXX unused code
539
540 showSet :: (Show a) => [a] -> ShowS
541 showSet []
542 = showString "{}"
543 showSet (x:xs)
544 = showChar '{' . shows x . showTail xs
545 where
546 showTail [] = showChar '}'
547 showTail (x':xs') = showChar ',' . shows x' . showTail xs'
548 -}
549
550 {--------------------------------------------------------------------
551 Read
552 --------------------------------------------------------------------}
553 instance (Read a, Ord a) => Read (Set a) where
554 #ifdef __GLASGOW_HASKELL__
555 readPrec = parens $ prec 10 $ do
556 Ident "fromList" <- lexP
557 xs <- readPrec
558 return (fromList xs)
559
560 readListPrec = readListPrecDefault
561 #else
562 readsPrec p = readParen (p > 10) $ \ r -> do
563 ("fromList",s) <- lex r
564 (xs,t) <- reads s
565 return (fromList xs,t)
566 #endif
567
568 {--------------------------------------------------------------------
569 Typeable/Data
570 --------------------------------------------------------------------}
571
572 #include "Typeable.h"
573 INSTANCE_TYPEABLE1(Set,setTc,"Set")
574
575 {--------------------------------------------------------------------
576 Utility functions that return sub-ranges of the original
577 tree. Some functions take a comparison function as argument to
578 allow comparisons against infinite values. A function [cmplo x]
579 should be read as [compare lo x].
580
581 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
582 and [cmphi x == GT] for the value [x] of the root.
583 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
584 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
585
586 [split k t] Returns two trees [l] and [r] where all values
587 in [l] are <[k] and all keys in [r] are >[k].
588 [splitMember k t] Just like [split] but also returns whether [k]
589 was found in the tree.
590 --------------------------------------------------------------------}
591
592 {--------------------------------------------------------------------
593 [trim lo hi t] trims away all subtrees that surely contain no
594 values between the range [lo] to [hi]. The returned tree is either
595 empty or the key of the root is between @lo@ and @hi@.
596 --------------------------------------------------------------------}
597 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
598 trim _ _ Tip = Tip
599 trim cmplo cmphi t@(Bin _ x l r)
600 = case cmplo x of
601 LT -> case cmphi x of
602 GT -> t
603 _ -> trim cmplo cmphi l
604 _ -> trim cmplo cmphi r
605
606 {-
607 XXX unused code
608
609 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
610 trimMemberLo _ _ Tip = (False,Tip)
611 trimMemberLo lo cmphi t@(Bin _ x l r)
612 = case compare lo x of
613 LT -> case cmphi x of
614 GT -> (member lo t, t)
615 _ -> trimMemberLo lo cmphi l
616 GT -> trimMemberLo lo cmphi r
617 EQ -> (True,trim (compare lo) cmphi r)
618 -}
619
620 {--------------------------------------------------------------------
621 [filterGt x t] filter all values >[x] from tree [t]
622 [filterLt x t] filter all values <[x] from tree [t]
623 --------------------------------------------------------------------}
624 filterGt :: (a -> Ordering) -> Set a -> Set a
625 filterGt _ Tip = Tip
626 filterGt cmp (Bin _ x l r)
627 = case cmp x of
628 LT -> join x (filterGt cmp l) r
629 GT -> filterGt cmp r
630 EQ -> r
631
632 filterLt :: (a -> Ordering) -> Set a -> Set a
633 filterLt _ Tip = Tip
634 filterLt cmp (Bin _ x l r)
635 = case cmp x of
636 LT -> filterLt cmp l
637 GT -> join x l (filterLt cmp r)
638 EQ -> l
639
640
641 {--------------------------------------------------------------------
642 Split
643 --------------------------------------------------------------------}
644 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
645 -- where all elements in @set1@ are lower than @x@ and all elements in
646 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
647 split :: Ord a => a -> Set a -> (Set a,Set a)
648 split _ Tip = (Tip,Tip)
649 split x (Bin _ y l r)
650 = case compare x y of
651 LT -> let (lt,gt) = split x l in (lt,join y gt r)
652 GT -> let (lt,gt) = split x r in (join y l lt,gt)
653 EQ -> (l,r)
654
655 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
656 -- element was found in the original set.
657 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
658 splitMember x t = let (l,m,r) = splitLookup x t in
659 (l,maybe False (const True) m,r)
660
661 -- | /O(log n)/. Performs a 'split' but also returns the pivot
662 -- element that was found in the original set.
663 splitLookup :: Ord a => a -> Set a -> (Set a,Maybe a,Set a)
664 splitLookup _ Tip = (Tip,Nothing,Tip)
665 splitLookup x (Bin _ y l r)
666 = case compare x y of
667 LT -> let (lt,found,gt) = splitLookup x l in (lt,found,join y gt r)
668 GT -> let (lt,found,gt) = splitLookup x r in (join y l lt,found,gt)
669 EQ -> (l,Just y,r)
670
671 {--------------------------------------------------------------------
672 Utility functions that maintain the balance properties of the tree.
673 All constructors assume that all values in [l] < [x] and all values
674 in [r] > [x], and that [l] and [r] are valid trees.
675
676 In order of sophistication:
677 [Bin sz x l r] The type constructor.
678 [bin x l r] Maintains the correct size, assumes that both [l]
679 and [r] are balanced with respect to each other.
680 [balance x l r] Restores the balance and size.
681 Assumes that the original tree was balanced and
682 that [l] or [r] has changed by at most one element.
683 [join x l r] Restores balance and size.
684
685 Furthermore, we can construct a new tree from two trees. Both operations
686 assume that all values in [l] < all values in [r] and that [l] and [r]
687 are valid:
688 [glue l r] Glues [l] and [r] together. Assumes that [l] and
689 [r] are already balanced with respect to each other.
690 [merge l r] Merges two trees and restores balance.
691
692 Note: in contrast to Adam's paper, we use (<=) comparisons instead
693 of (<) comparisons in [join], [merge] and [balance].
694 Quickcheck (on [difference]) showed that this was necessary in order
695 to maintain the invariants. It is quite unsatisfactory that I haven't
696 been able to find out why this is actually the case! Fortunately, it
697 doesn't hurt to be a bit more conservative.
698 --------------------------------------------------------------------}
699
700 {--------------------------------------------------------------------
701 Join
702 --------------------------------------------------------------------}
703 join :: a -> Set a -> Set a -> Set a
704 join x Tip r = insertMin x r
705 join x l Tip = insertMax x l
706 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
707 | delta*sizeL <= sizeR = balance z (join x l lz) rz
708 | delta*sizeR <= sizeL = balance y ly (join x ry r)
709 | otherwise = bin x l r
710
711
712 -- insertMin and insertMax don't perform potentially expensive comparisons.
713 insertMax,insertMin :: a -> Set a -> Set a
714 insertMax x t
715 = case t of
716 Tip -> singleton x
717 Bin _ y l r
718 -> balance y l (insertMax x r)
719
720 insertMin x t
721 = case t of
722 Tip -> singleton x
723 Bin _ y l r
724 -> balance y (insertMin x l) r
725
726 {--------------------------------------------------------------------
727 [merge l r]: merges two trees.
728 --------------------------------------------------------------------}
729 merge :: Set a -> Set a -> Set a
730 merge Tip r = r
731 merge l Tip = l
732 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
733 | delta*sizeL <= sizeR = balance y (merge l ly) ry
734 | delta*sizeR <= sizeL = balance x lx (merge rx r)
735 | otherwise = glue l r
736
737 {--------------------------------------------------------------------
738 [glue l r]: glues two trees together.
739 Assumes that [l] and [r] are already balanced with respect to each other.
740 --------------------------------------------------------------------}
741 glue :: Set a -> Set a -> Set a
742 glue Tip r = r
743 glue l Tip = l
744 glue l r
745 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
746 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
747
748
749 -- | /O(log n)/. Delete and find the minimal element.
750 --
751 -- > deleteFindMin set = (findMin set, deleteMin set)
752
753 deleteFindMin :: Set a -> (a,Set a)
754 deleteFindMin t
755 = case t of
756 Bin _ x Tip r -> (x,r)
757 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
758 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
759
760 -- | /O(log n)/. Delete and find the maximal element.
761 --
762 -- > deleteFindMax set = (findMax set, deleteMax set)
763 deleteFindMax :: Set a -> (a,Set a)
764 deleteFindMax t
765 = case t of
766 Bin _ x l Tip -> (x,l)
767 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
768 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
769
770 -- | /O(log n)/. Retrieves the minimal key of the set, and the set stripped from that element
771 -- @fail@s (in the monad) when passed an empty set.
772 minView :: Monad m => Set a -> m (a, Set a)
773 minView Tip = fail "Set.minView: empty set"
774 minView x = return (deleteFindMin x)
775
776 -- | /O(log n)/. Retrieves the maximal key of the set, and the set stripped from that element
777 -- @fail@s (in the monad) when passed an empty set.
778 maxView :: Monad m => Set a -> m (a, Set a)
779 maxView Tip = fail "Set.maxView: empty set"
780 maxView x = return (deleteFindMax x)
781
782
783 {--------------------------------------------------------------------
784 [balance x l r] balances two trees with value x.
785 The sizes of the trees should balance after decreasing the
786 size of one of them. (a rotation).
787
788 [delta] is the maximal relative difference between the sizes of
789 two trees, it corresponds with the [w] in Adams' paper,
790 or equivalently, [1/delta] corresponds with the $\alpha$
791 in Nievergelt's paper. Adams shows that [delta] should
792 be larger than 3.745 in order to garantee that the
793 rotations can always restore balance.
794
795 [ratio] is the ratio between an outer and inner sibling of the
796 heavier subtree in an unbalanced setting. It determines
797 whether a double or single rotation should be performed
798 to restore balance. It is correspondes with the inverse
799 of $\alpha$ in Adam's article.
800
801 Note that:
802 - [delta] should be larger than 4.646 with a [ratio] of 2.
803 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
804
805 - A lower [delta] leads to a more 'perfectly' balanced tree.
806 - A higher [delta] performs less rebalancing.
807
808 - Balancing is automatic for random data and a balancing
809 scheme is only necessary to avoid pathological worst cases.
810 Almost any choice will do in practice
811
812 - Allthough it seems that a rather large [delta] may perform better
813 than smaller one, measurements have shown that the smallest [delta]
814 of 4 is actually the fastest on a wide range of operations. It
815 especially improves performance on worst-case scenarios like
816 a sequence of ordered insertions.
817
818 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
819 to decide whether a single or double rotation is needed. Allthough
820 he actually proves that this ratio is needed to maintain the
821 invariants, his implementation uses a (invalid) ratio of 1.
822 He is aware of the problem though since he has put a comment in his
823 original source code that he doesn't care about generating a
824 slightly inbalanced tree since it doesn't seem to matter in practice.
825 However (since we use quickcheck :-) we will stick to strictly balanced
826 trees.
827 --------------------------------------------------------------------}
828 delta,ratio :: Int
829 delta = 4
830 ratio = 2
831
832 balance :: a -> Set a -> Set a -> Set a
833 balance x l r
834 | sizeL + sizeR <= 1 = Bin sizeX x l r
835 | sizeR >= delta*sizeL = rotateL x l r
836 | sizeL >= delta*sizeR = rotateR x l r
837 | otherwise = Bin sizeX x l r
838 where
839 sizeL = size l
840 sizeR = size r
841 sizeX = sizeL + sizeR + 1
842
843 -- rotate
844 rotateL :: a -> Set a -> Set a -> Set a
845 rotateL x l r@(Bin _ _ ly ry)
846 | size ly < ratio*size ry = singleL x l r
847 | otherwise = doubleL x l r
848 rotateL _ _ Tip = error "rotateL Tip"
849
850 rotateR :: a -> Set a -> Set a -> Set a
851 rotateR x l@(Bin _ _ ly ry) r
852 | size ry < ratio*size ly = singleR x l r
853 | otherwise = doubleR x l r
854 rotateR _ Tip _ = error "rotateL Tip"
855
856 -- basic rotations
857 singleL, singleR :: a -> Set a -> Set a -> Set a
858 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
859 singleL _ _ Tip = error "singleL"
860 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
861 singleR _ Tip _ = error "singleR"
862
863 doubleL, doubleR :: a -> Set a -> Set a -> Set a
864 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
865 doubleL _ _ _ = error "doubleL"
866 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
867 doubleR _ _ _ = error "doubleR"
868
869
870 {--------------------------------------------------------------------
871 The bin constructor maintains the size of the tree
872 --------------------------------------------------------------------}
873 bin :: a -> Set a -> Set a -> Set a
874 bin x l r
875 = Bin (size l + size r + 1) x l r
876
877
878 {--------------------------------------------------------------------
879 Utilities
880 --------------------------------------------------------------------}
881 foldlStrict :: (a -> b -> a) -> a -> [b] -> a
882 foldlStrict f z xs
883 = case xs of
884 [] -> z
885 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
886
887
888 {--------------------------------------------------------------------
889 Debugging
890 --------------------------------------------------------------------}
891 -- | /O(n)/. Show the tree that implements the set. The tree is shown
892 -- in a compressed, hanging format.
893 showTree :: Show a => Set a -> String
894 showTree s
895 = showTreeWith True False s
896
897
898 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
899 the tree that implements the set. If @hang@ is
900 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
901 @wide@ is 'True', an extra wide version is shown.
902
903 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
904 > 4
905 > +--2
906 > | +--1
907 > | +--3
908 > +--5
909 >
910 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
911 > 4
912 > |
913 > +--2
914 > | |
915 > | +--1
916 > | |
917 > | +--3
918 > |
919 > +--5
920 >
921 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
922 > +--5
923 > |
924 > 4
925 > |
926 > | +--3
927 > | |
928 > +--2
929 > |
930 > +--1
931
932 -}
933 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
934 showTreeWith hang wide t
935 | hang = (showsTreeHang wide [] t) ""
936 | otherwise = (showsTree wide [] [] t) ""
937
938 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
939 showsTree wide lbars rbars t
940 = case t of
941 Tip -> showsBars lbars . showString "|\n"
942 Bin _ x Tip Tip
943 -> showsBars lbars . shows x . showString "\n"
944 Bin _ x l r
945 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
946 showWide wide rbars .
947 showsBars lbars . shows x . showString "\n" .
948 showWide wide lbars .
949 showsTree wide (withEmpty lbars) (withBar lbars) l
950
951 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
952 showsTreeHang wide bars t
953 = case t of
954 Tip -> showsBars bars . showString "|\n"
955 Bin _ x Tip Tip
956 -> showsBars bars . shows x . showString "\n"
957 Bin _ x l r
958 -> showsBars bars . shows x . showString "\n" .
959 showWide wide bars .
960 showsTreeHang wide (withBar bars) l .
961 showWide wide bars .
962 showsTreeHang wide (withEmpty bars) r
963
964 showWide :: Bool -> [String] -> String -> String
965 showWide wide bars
966 | wide = showString (concat (reverse bars)) . showString "|\n"
967 | otherwise = id
968
969 showsBars :: [String] -> ShowS
970 showsBars bars
971 = case bars of
972 [] -> id
973 _ -> showString (concat (reverse (tail bars))) . showString node
974
975 node :: String
976 node = "+--"
977
978 withBar, withEmpty :: [String] -> [String]
979 withBar bars = "| ":bars
980 withEmpty bars = " ":bars
981
982 {--------------------------------------------------------------------
983 Assertions
984 --------------------------------------------------------------------}
985 -- | /O(n)/. Test if the internal set structure is valid.
986 valid :: Ord a => Set a -> Bool
987 valid t
988 = balanced t && ordered t && validsize t
989
990 ordered :: Ord a => Set a -> Bool
991 ordered t
992 = bounded (const True) (const True) t
993 where
994 bounded lo hi t'
995 = case t' of
996 Tip -> True
997 Bin _ x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
998
999 balanced :: Set a -> Bool
1000 balanced t
1001 = case t of
1002 Tip -> True
1003 Bin _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1004 balanced l && balanced r
1005
1006 validsize :: Set a -> Bool
1007 validsize t
1008 = (realsize t == Just (size t))
1009 where
1010 realsize t'
1011 = case t' of
1012 Tip -> Just 0
1013 Bin sz _ l r -> case (realsize l,realsize r) of
1014 (Just n,Just m) | n+m+1 == sz -> Just sz
1015 _ -> Nothing
1016
1017 {-
1018 {--------------------------------------------------------------------
1019 Testing
1020 --------------------------------------------------------------------}
1021 testTree :: [Int] -> Set Int
1022 testTree xs = fromList xs
1023 test1 = testTree [1..20]
1024 test2 = testTree [30,29..10]
1025 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1026
1027 {--------------------------------------------------------------------
1028 QuickCheck
1029 --------------------------------------------------------------------}
1030 qcheck prop
1031 = check config prop
1032 where
1033 config = Config
1034 { configMaxTest = 500
1035 , configMaxFail = 5000
1036 , configSize = \n -> (div n 2 + 3)
1037 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1038 }
1039
1040
1041 {--------------------------------------------------------------------
1042 Arbitrary, reasonably balanced trees
1043 --------------------------------------------------------------------}
1044 instance (Enum a) => Arbitrary (Set a) where
1045 arbitrary = sized (arbtree 0 maxkey)
1046 where maxkey = 10000
1047
1048 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
1049 arbtree lo hi n
1050 | n <= 0 = return Tip
1051 | lo >= hi = return Tip
1052 | otherwise = do{ i <- choose (lo,hi)
1053 ; m <- choose (1,30)
1054 ; let (ml,mr) | m==(1::Int)= (1,2)
1055 | m==2 = (2,1)
1056 | m==3 = (1,1)
1057 | otherwise = (2,2)
1058 ; l <- arbtree lo (i-1) (n `div` ml)
1059 ; r <- arbtree (i+1) hi (n `div` mr)
1060 ; return (bin (toEnum i) l r)
1061 }
1062
1063
1064 {--------------------------------------------------------------------
1065 Valid tree's
1066 --------------------------------------------------------------------}
1067 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1068 forValid f
1069 = forAll arbitrary $ \t ->
1070 -- classify (balanced t) "balanced" $
1071 classify (size t == 0) "empty" $
1072 classify (size t > 0 && size t <= 10) "small" $
1073 classify (size t > 10 && size t <= 64) "medium" $
1074 classify (size t > 64) "large" $
1075 balanced t ==> f t
1076
1077 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1078 forValidIntTree f
1079 = forValid f
1080
1081 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1082 forValidUnitTree f
1083 = forValid f
1084
1085
1086 prop_Valid
1087 = forValidUnitTree $ \t -> valid t
1088
1089 {--------------------------------------------------------------------
1090 Single, Insert, Delete
1091 --------------------------------------------------------------------}
1092 prop_Single :: Int -> Bool
1093 prop_Single x
1094 = (insert x empty == singleton x)
1095
1096 prop_InsertValid :: Int -> Property
1097 prop_InsertValid k
1098 = forValidUnitTree $ \t -> valid (insert k t)
1099
1100 prop_InsertDelete :: Int -> Set Int -> Property
1101 prop_InsertDelete k t
1102 = not (member k t) ==> delete k (insert k t) == t
1103
1104 prop_DeleteValid :: Int -> Property
1105 prop_DeleteValid k
1106 = forValidUnitTree $ \t ->
1107 valid (delete k (insert k t))
1108
1109 {--------------------------------------------------------------------
1110 Balance
1111 --------------------------------------------------------------------}
1112 prop_Join :: Int -> Property
1113 prop_Join x
1114 = forValidUnitTree $ \t ->
1115 let (l,r) = split x t
1116 in valid (join x l r)
1117
1118 prop_Merge :: Int -> Property
1119 prop_Merge x
1120 = forValidUnitTree $ \t ->
1121 let (l,r) = split x t
1122 in valid (merge l r)
1123
1124
1125 {--------------------------------------------------------------------
1126 Union
1127 --------------------------------------------------------------------}
1128 prop_UnionValid :: Property
1129 prop_UnionValid
1130 = forValidUnitTree $ \t1 ->
1131 forValidUnitTree $ \t2 ->
1132 valid (union t1 t2)
1133
1134 prop_UnionInsert :: Int -> Set Int -> Bool
1135 prop_UnionInsert x t
1136 = union t (singleton x) == insert x t
1137
1138 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1139 prop_UnionAssoc t1 t2 t3
1140 = union t1 (union t2 t3) == union (union t1 t2) t3
1141
1142 prop_UnionComm :: Set Int -> Set Int -> Bool
1143 prop_UnionComm t1 t2
1144 = (union t1 t2 == union t2 t1)
1145
1146
1147 prop_DiffValid
1148 = forValidUnitTree $ \t1 ->
1149 forValidUnitTree $ \t2 ->
1150 valid (difference t1 t2)
1151
1152 prop_Diff :: [Int] -> [Int] -> Bool
1153 prop_Diff xs ys
1154 = toAscList (difference (fromList xs) (fromList ys))
1155 == List.sort ((List.\\) (nub xs) (nub ys))
1156
1157 prop_IntValid
1158 = forValidUnitTree $ \t1 ->
1159 forValidUnitTree $ \t2 ->
1160 valid (intersection t1 t2)
1161
1162 prop_Int :: [Int] -> [Int] -> Bool
1163 prop_Int xs ys
1164 = toAscList (intersection (fromList xs) (fromList ys))
1165 == List.sort (nub ((List.intersect) (xs) (ys)))
1166
1167 {--------------------------------------------------------------------
1168 Lists
1169 --------------------------------------------------------------------}
1170 prop_Ordered
1171 = forAll (choose (5,100)) $ \n ->
1172 let xs = [0..n::Int]
1173 in fromAscList xs == fromList xs
1174
1175 prop_List :: [Int] -> Bool
1176 prop_List xs
1177 = (sort (nub xs) == toList (fromList xs))
1178 -}