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