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