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