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