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