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