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