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