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