Remove System.Posix.Signals (moving to unix)
[ghc-base.git] / Data / Set.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Set
4 -- Copyright   :  (c) Daan Leijen 2002
5 -- License     :  BSD-style
6 -- Maintainer  :  libraries@haskell.org
7 -- Stability   :  provisional
8 -- Portability :  portable
9 --
10 -- An efficient implementation of sets.
11 --
12 -- Since many function names (but not the type name) clash with
13 -- "Prelude" names, this module is usually imported @qualified@, e.g.
14 --
15 -- >  import Data.Set (Set)
16 -- >  import qualified Data.Set as Set
17 --
18 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
19 -- trees of /bounded balance/) as described by:
20 --
21 --    * Stephen Adams, \"/Efficient sets: a balancing act/\",
22 --      Journal of Functional Programming 3(4):553-562, October 1993,
23 --      <http://www.swiss.ai.mit.edu/~adams/BB>.
24 --
25 --    * J. Nievergelt and E.M. Reingold,
26 --      \"/Binary search trees of bounded balance/\",
27 --      SIAM journal of computing 2(1), March 1973.
28 --
29 -- Note that the implementation is /left-biased/ -- the elements of a
30 -- first argument are always preferred to the second, for example in
31 -- 'union' or 'insert'.  Of course, left-biasing can only be observed
32 -- when equality is an equivalence relation instead of structural
33 -- equality.
34 -----------------------------------------------------------------------------
35
36 module Data.Set  ( 
37             -- * Set type
38               Set          -- instance Eq,Ord,Show,Read,Data,Typeable
39
40             -- * Operators
41             , (\\)
42
43             -- * Query
44             , null
45             , size
46             , member
47             , notMember
48             , isSubsetOf
49             , isProperSubsetOf
50             
51             -- * Construction
52             , empty
53             , singleton
54             , insert
55             , delete
56             
57             -- * Combine
58             , union, unions
59             , difference
60             , intersection
61             
62             -- * Filter
63             , filter
64             , partition
65             , split
66             , splitMember
67
68             -- * Map
69             , map
70             , mapMonotonic
71
72             -- * Fold
73             , fold
74
75             -- * Min\/Max
76             , findMin
77             , findMax
78             , deleteMin
79             , deleteMax
80             , deleteFindMin
81             , deleteFindMax
82             , maxView
83             , minView
84
85             -- * Conversion
86
87             -- ** List
88             , elems
89             , toList
90             , fromList
91             
92             -- ** Ordered list
93             , toAscList
94             , fromAscList
95             , fromDistinctAscList
96                         
97             -- * Debugging
98             , showTree
99             , showTreeWith
100             , valid
101             ) where
102
103 import Prelude hiding (filter,foldr,null,map)
104 import qualified Data.List as List
105 import Data.Monoid (Monoid(..))
106 import Data.Typeable
107 import Data.Foldable (Foldable(foldMap))
108
109 {-
110 -- just for testing
111 import QuickCheck 
112 import List (nub,sort)
113 import qualified List
114 -}
115
116 #if __GLASGOW_HASKELL__
117 import Text.Read
118 import Data.Generics.Basics
119 import Data.Generics.Instances
120 #endif
121
122 {--------------------------------------------------------------------
123   Operators
124 --------------------------------------------------------------------}
125 infixl 9 \\ --
126
127 -- | /O(n+m)/. See 'difference'.
128 (\\) :: Ord a => Set a -> Set a -> Set a
129 m1 \\ m2 = difference m1 m2
130
131 {--------------------------------------------------------------------
132   Sets are size balanced trees
133 --------------------------------------------------------------------}
134 -- | A set of values @a@.
135 data Set a    = Tip 
136               | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a) 
137
138 type Size     = Int
139
140 instance Ord a => Monoid (Set a) where
141     mempty  = empty
142     mappend = union
143     mconcat = unions
144
145 instance Foldable Set where
146     foldMap f Tip = mempty
147     foldMap f (Bin _s k l r) = foldMap f l `mappend` f k `mappend` foldMap f r
148
149 #if __GLASGOW_HASKELL__
150
151 {--------------------------------------------------------------------
152   A Data instance  
153 --------------------------------------------------------------------}
154
155 -- This instance preserves data abstraction at the cost of inefficiency.
156 -- We omit reflection services for the sake of data abstraction.
157
158 instance (Data a, Ord a) => Data (Set a) where
159   gfoldl f z set = z fromList `f` (toList set)
160   toConstr _     = error "toConstr"
161   gunfold _ _    = error "gunfold"
162   dataTypeOf _   = mkNorepType "Data.Set.Set"
163   dataCast1 f    = gcast1 f
164
165 #endif
166
167 {--------------------------------------------------------------------
168   Query
169 --------------------------------------------------------------------}
170 -- | /O(1)/. Is this the empty set?
171 null :: Set a -> Bool
172 null t
173   = case t of
174       Tip           -> True
175       Bin sz x l r  -> False
176
177 -- | /O(1)/. The number of elements in the set.
178 size :: Set a -> Int
179 size t
180   = case t of
181       Tip           -> 0
182       Bin sz x l r  -> sz
183
184 -- | /O(log n)/. Is the element in the set?
185 member :: Ord a => a -> Set a -> Bool
186 member x t
187   = case t of
188       Tip -> False
189       Bin sz y l r
190           -> case compare x y of
191                LT -> member x l
192                GT -> member x r
193                EQ -> True       
194
195 -- | /O(log n)/. Is the element not in the set?
196 notMember :: Ord a => a -> Set a -> Bool
197 notMember x t = not $ member x t
198
199 {--------------------------------------------------------------------
200   Construction
201 --------------------------------------------------------------------}
202 -- | /O(1)/. The empty set.
203 empty  :: Set a
204 empty
205   = Tip
206
207 -- | /O(1)/. Create a singleton set.
208 singleton :: a -> Set a
209 singleton x 
210   = Bin 1 x Tip Tip
211
212 {--------------------------------------------------------------------
213   Insertion, Deletion
214 --------------------------------------------------------------------}
215 -- | /O(log n)/. Insert an element in a set.
216 -- If the set already contains an element equal to the given value,
217 -- it is replaced with the new value.
218 insert :: Ord a => a -> Set a -> Set a
219 insert x t
220   = case t of
221       Tip -> singleton x
222       Bin sz y l r
223           -> case compare x y of
224                LT -> balance y (insert x l) r
225                GT -> balance y l (insert x r)
226                EQ -> Bin sz x l r
227
228
229 -- | /O(log n)/. Delete an element from a set.
230 delete :: Ord a => a -> Set a -> Set a
231 delete x t
232   = case t of
233       Tip -> Tip
234       Bin sz y l r 
235           -> case compare x y of
236                LT -> balance y (delete x l) r
237                GT -> balance y l (delete x r)
238                EQ -> glue l r
239
240 {--------------------------------------------------------------------
241   Subset
242 --------------------------------------------------------------------}
243 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
244 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
245 isProperSubsetOf s1 s2
246     = (size s1 < size s2) && (isSubsetOf s1 s2)
247
248
249 -- | /O(n+m)/. Is this a subset?
250 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
251 isSubsetOf :: Ord a => Set a -> Set a -> Bool
252 isSubsetOf t1 t2
253   = (size t1 <= size t2) && (isSubsetOfX t1 t2)
254
255 isSubsetOfX Tip t = True
256 isSubsetOfX t Tip = False
257 isSubsetOfX (Bin _ x l r) t
258   = found && isSubsetOfX l lt && isSubsetOfX r gt
259   where
260     (lt,found,gt) = splitMember x t
261
262
263 {--------------------------------------------------------------------
264   Minimal, Maximal
265 --------------------------------------------------------------------}
266 -- | /O(log n)/. The minimal element of a set.
267 findMin :: Set a -> a
268 findMin (Bin _ x Tip r) = x
269 findMin (Bin _ x l r)   = findMin l
270 findMin Tip             = error "Set.findMin: empty set has no minimal element"
271
272 -- | /O(log n)/. The maximal element of a set.
273 findMax :: Set a -> a
274 findMax (Bin _ x l Tip)  = x
275 findMax (Bin _ x l r)    = findMax r
276 findMax Tip              = error "Set.findMax: empty set has no maximal element"
277
278 -- | /O(log n)/. Delete the minimal element.
279 deleteMin :: Set a -> Set a
280 deleteMin (Bin _ x Tip r) = r
281 deleteMin (Bin _ x l r)   = balance x (deleteMin l) r
282 deleteMin Tip             = Tip
283
284 -- | /O(log n)/. Delete the maximal element.
285 deleteMax :: Set a -> Set a
286 deleteMax (Bin _ x l Tip) = l
287 deleteMax (Bin _ x l r)   = balance x l (deleteMax r)
288 deleteMax Tip             = Tip
289
290
291 {--------------------------------------------------------------------
292   Union. 
293 --------------------------------------------------------------------}
294 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
295 unions :: Ord a => [Set a] -> Set a
296 unions ts
297   = foldlStrict union empty ts
298
299
300 -- | /O(n+m)/. The union of two sets, preferring the first set when
301 -- equal elements are encountered.
302 -- The implementation uses the efficient /hedge-union/ algorithm.
303 -- Hedge-union is more efficient on (bigset `union` smallset).
304 union :: Ord a => Set a -> Set a -> Set a
305 union Tip t2  = t2
306 union t1 Tip  = t1
307 union t1 t2 = hedgeUnion (const LT) (const GT) t1 t2
308
309 hedgeUnion cmplo cmphi t1 Tip 
310   = t1
311 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
312   = join x (filterGt cmplo l) (filterLt cmphi r)
313 hedgeUnion cmplo cmphi (Bin _ x l r) t2
314   = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2)) 
315            (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
316   where
317     cmpx y  = compare x y
318
319 {--------------------------------------------------------------------
320   Difference
321 --------------------------------------------------------------------}
322 -- | /O(n+m)/. Difference of two sets. 
323 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
324 difference :: Ord a => Set a -> Set a -> Set a
325 difference Tip t2  = Tip
326 difference t1 Tip  = t1
327 difference t1 t2   = hedgeDiff (const LT) (const GT) t1 t2
328
329 hedgeDiff cmplo cmphi Tip t     
330   = Tip
331 hedgeDiff cmplo cmphi (Bin _ x l r) Tip 
332   = join x (filterGt cmplo l) (filterLt cmphi r)
333 hedgeDiff cmplo cmphi t (Bin _ x l r) 
334   = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l) 
335           (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
336   where
337     cmpx y = compare x y
338
339 {--------------------------------------------------------------------
340   Intersection
341 --------------------------------------------------------------------}
342 -- | /O(n+m)/. The intersection of two sets.
343 -- Elements of the result come from the first set, so for example
344 --
345 -- > import qualified Data.Set as S
346 -- > data AB = A | B deriving Show
347 -- > instance Ord AB where compare _ _ = EQ
348 -- > instance Eq AB where _ == _ = True
349 -- > main = print (S.singleton A `S.intersection` S.singleton B,
350 -- >               S.singleton B `S.intersection` S.singleton A)
351 --
352 -- prints @(fromList [A],fromList [B])@.
353 intersection :: Ord a => Set a -> Set a -> Set a
354 intersection Tip t = Tip
355 intersection t Tip = Tip
356 intersection t1@(Bin s1 x1 l1 r1) t2@(Bin s2 x2 l2 r2) =
357    if s1 >= s2 then
358       let (lt,found,gt) = splitLookup x2 t1
359           tl            = intersection lt l2
360           tr            = intersection gt r2
361       in case found of
362       Just x -> join x tl tr
363       Nothing -> merge tl tr
364    else let (lt,found,gt) = splitMember x1 t2
365             tl            = intersection l1 lt
366             tr            = intersection r1 gt
367         in if found then join x1 tl tr
368            else merge tl tr
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 t = let (l,m,r) = splitLookup x t in
645      (l,maybe False (const True) m,r)
646
647 -- | /O(log n)/. Performs a 'split' but also returns the pivot
648 -- element that was found in the original set.
649 splitLookup :: Ord a => a -> Set a -> (Set a,Maybe a,Set a)
650 splitLookup x Tip = (Tip,Nothing,Tip)
651 splitLookup x (Bin sy y l r)
652    = case compare x y of
653        LT -> let (lt,found,gt) = splitLookup x l in (lt,found,join y gt r)
654        GT -> let (lt,found,gt) = splitLookup x r in (join y l lt,found,gt)
655        EQ -> (l,Just y,r)
656
657 {--------------------------------------------------------------------
658   Utility functions that maintain the balance properties of the tree.
659   All constructors assume that all values in [l] < [x] and all values
660   in [r] > [x], and that [l] and [r] are valid trees.
661   
662   In order of sophistication:
663     [Bin sz x l r]    The type constructor.
664     [bin x l r]       Maintains the correct size, assumes that both [l]
665                       and [r] are balanced with respect to each other.
666     [balance x l r]   Restores the balance and size.
667                       Assumes that the original tree was balanced and
668                       that [l] or [r] has changed by at most one element.
669     [join x l r]      Restores balance and size. 
670
671   Furthermore, we can construct a new tree from two trees. Both operations
672   assume that all values in [l] < all values in [r] and that [l] and [r]
673   are valid:
674     [glue l r]        Glues [l] and [r] together. Assumes that [l] and
675                       [r] are already balanced with respect to each other.
676     [merge l r]       Merges two trees and restores balance.
677
678   Note: in contrast to Adam's paper, we use (<=) comparisons instead
679   of (<) comparisons in [join], [merge] and [balance]. 
680   Quickcheck (on [difference]) showed that this was necessary in order 
681   to maintain the invariants. It is quite unsatisfactory that I haven't 
682   been able to find out why this is actually the case! Fortunately, it 
683   doesn't hurt to be a bit more conservative.
684 --------------------------------------------------------------------}
685
686 {--------------------------------------------------------------------
687   Join 
688 --------------------------------------------------------------------}
689 join :: a -> Set a -> Set a -> Set a
690 join x Tip r  = insertMin x r
691 join x l Tip  = insertMax x l
692 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
693   | delta*sizeL <= sizeR  = balance z (join x l lz) rz
694   | delta*sizeR <= sizeL  = balance y ly (join x ry r)
695   | otherwise             = bin x l r
696
697
698 -- insertMin and insertMax don't perform potentially expensive comparisons.
699 insertMax,insertMin :: a -> Set a -> Set a 
700 insertMax x t
701   = case t of
702       Tip -> singleton x
703       Bin sz y l r
704           -> balance y l (insertMax x r)
705              
706 insertMin x t
707   = case t of
708       Tip -> singleton x
709       Bin sz y l r
710           -> balance y (insertMin x l) r
711              
712 {--------------------------------------------------------------------
713   [merge l r]: merges two trees.
714 --------------------------------------------------------------------}
715 merge :: Set a -> Set a -> Set a
716 merge Tip r   = r
717 merge l Tip   = l
718 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
719   | delta*sizeL <= sizeR = balance y (merge l ly) ry
720   | delta*sizeR <= sizeL = balance x lx (merge rx r)
721   | otherwise            = glue l r
722
723 {--------------------------------------------------------------------
724   [glue l r]: glues two trees together.
725   Assumes that [l] and [r] are already balanced with respect to each other.
726 --------------------------------------------------------------------}
727 glue :: Set a -> Set a -> Set a
728 glue Tip r = r
729 glue l Tip = l
730 glue l r   
731   | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
732   | otherwise       = let (m,r') = deleteFindMin r in balance m l r'
733
734
735 -- | /O(log n)/. Delete and find the minimal element.
736 -- 
737 -- > deleteFindMin set = (findMin set, deleteMin set)
738
739 deleteFindMin :: Set a -> (a,Set a)
740 deleteFindMin t 
741   = case t of
742       Bin _ x Tip r -> (x,r)
743       Bin _ x l r   -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
744       Tip           -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
745
746 -- | /O(log n)/. Delete and find the maximal element.
747 -- 
748 -- > deleteFindMax set = (findMax set, deleteMax set)
749 deleteFindMax :: Set a -> (a,Set a)
750 deleteFindMax t
751   = case t of
752       Bin _ x l Tip -> (x,l)
753       Bin _ x l r   -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
754       Tip           -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
755
756 -- | /O(log n)/. Retrieves the minimal key of the set, and the set stripped from that element
757 -- @fail@s (in the monad) when passed an empty set.
758 minView :: Monad m => Set a -> m (a, Set a)
759 minView Tip = fail "Set.minView: empty set"
760 minView x = return (deleteFindMin x)
761
762 -- | /O(log n)/. Retrieves the maximal key of the set, and the set stripped from that element
763 -- @fail@s (in the monad) when passed an empty set.
764 maxView :: Monad m => Set a -> m (a, Set a)
765 maxView Tip = fail "Set.maxView: empty set"
766 maxView x = return (deleteFindMax x)
767
768
769 {--------------------------------------------------------------------
770   [balance x l r] balances two trees with value x.
771   The sizes of the trees should balance after decreasing the
772   size of one of them. (a rotation).
773
774   [delta] is the maximal relative difference between the sizes of
775           two trees, it corresponds with the [w] in Adams' paper,
776           or equivalently, [1/delta] corresponds with the $\alpha$
777           in Nievergelt's paper. Adams shows that [delta] should
778           be larger than 3.745 in order to garantee that the
779           rotations can always restore balance.         
780
781   [ratio] is the ratio between an outer and inner sibling of the
782           heavier subtree in an unbalanced setting. It determines
783           whether a double or single rotation should be performed
784           to restore balance. It is correspondes with the inverse
785           of $\alpha$ in Adam's article.
786
787   Note that:
788   - [delta] should be larger than 4.646 with a [ratio] of 2.
789   - [delta] should be larger than 3.745 with a [ratio] of 1.534.
790   
791   - A lower [delta] leads to a more 'perfectly' balanced tree.
792   - A higher [delta] performs less rebalancing.
793
794   - Balancing is automatic for random data and a balancing
795     scheme is only necessary to avoid pathological worst cases.
796     Almost any choice will do in practice
797     
798   - Allthough it seems that a rather large [delta] may perform better 
799     than smaller one, measurements have shown that the smallest [delta]
800     of 4 is actually the fastest on a wide range of operations. It
801     especially improves performance on worst-case scenarios like
802     a sequence of ordered insertions.
803
804   Note: in contrast to Adams' paper, we use a ratio of (at least) 2
805   to decide whether a single or double rotation is needed. Allthough
806   he actually proves that this ratio is needed to maintain the
807   invariants, his implementation uses a (invalid) ratio of 1. 
808   He is aware of the problem though since he has put a comment in his 
809   original source code that he doesn't care about generating a 
810   slightly inbalanced tree since it doesn't seem to matter in practice. 
811   However (since we use quickcheck :-) we will stick to strictly balanced 
812   trees.
813 --------------------------------------------------------------------}
814 delta,ratio :: Int
815 delta = 4
816 ratio = 2
817
818 balance :: a -> Set a -> Set a -> Set a
819 balance x l r
820   | sizeL + sizeR <= 1    = Bin sizeX x l r
821   | sizeR >= delta*sizeL  = rotateL x l r
822   | sizeL >= delta*sizeR  = rotateR x l r
823   | otherwise             = Bin sizeX x l r
824   where
825     sizeL = size l
826     sizeR = size r
827     sizeX = sizeL + sizeR + 1
828
829 -- rotate
830 rotateL x l r@(Bin _ _ ly ry)
831   | size ly < ratio*size ry = singleL x l r
832   | otherwise               = doubleL x l r
833
834 rotateR x l@(Bin _ _ ly ry) r
835   | size ry < ratio*size ly = singleR x l r
836   | otherwise               = doubleR x l r
837
838 -- basic rotations
839 singleL x1 t1 (Bin _ x2 t2 t3)  = bin x2 (bin x1 t1 t2) t3
840 singleR x1 (Bin _ x2 t1 t2) t3  = bin x2 t1 (bin x1 t2 t3)
841
842 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
843 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
844
845
846 {--------------------------------------------------------------------
847   The bin constructor maintains the size of the tree
848 --------------------------------------------------------------------}
849 bin :: a -> Set a -> Set a -> Set a
850 bin x l r
851   = Bin (size l + size r + 1) x l r
852
853
854 {--------------------------------------------------------------------
855   Utilities
856 --------------------------------------------------------------------}
857 foldlStrict f z xs
858   = case xs of
859       []     -> z
860       (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
861
862
863 {--------------------------------------------------------------------
864   Debugging
865 --------------------------------------------------------------------}
866 -- | /O(n)/. Show the tree that implements the set. The tree is shown
867 -- in a compressed, hanging format.
868 showTree :: Show a => Set a -> String
869 showTree s
870   = showTreeWith True False s
871
872
873 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
874  the tree that implements the set. If @hang@ is
875  @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
876  @wide@ is 'True', an extra wide version is shown.
877
878 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
879 > 4
880 > +--2
881 > |  +--1
882 > |  +--3
883 > +--5
884
885 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
886 > 4
887 > |
888 > +--2
889 > |  |
890 > |  +--1
891 > |  |
892 > |  +--3
893 > |
894 > +--5
895
896 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
897 > +--5
898 > |
899 > 4
900 > |
901 > |  +--3
902 > |  |
903 > +--2
904 >    |
905 >    +--1
906
907 -}
908 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
909 showTreeWith hang wide t
910   | hang      = (showsTreeHang wide [] t) ""
911   | otherwise = (showsTree wide [] [] t) ""
912
913 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
914 showsTree wide lbars rbars t
915   = case t of
916       Tip -> showsBars lbars . showString "|\n"
917       Bin sz x Tip Tip
918           -> showsBars lbars . shows x . showString "\n" 
919       Bin sz x l r
920           -> showsTree wide (withBar rbars) (withEmpty rbars) r .
921              showWide wide rbars .
922              showsBars lbars . shows x . showString "\n" .
923              showWide wide lbars .
924              showsTree wide (withEmpty lbars) (withBar lbars) l
925
926 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
927 showsTreeHang wide bars t
928   = case t of
929       Tip -> showsBars bars . showString "|\n" 
930       Bin sz x Tip Tip
931           -> showsBars bars . shows x . showString "\n" 
932       Bin sz x l r
933           -> showsBars bars . shows x . showString "\n" . 
934              showWide wide bars .
935              showsTreeHang wide (withBar bars) l .
936              showWide wide bars .
937              showsTreeHang wide (withEmpty bars) r
938
939
940 showWide wide bars 
941   | wide      = showString (concat (reverse bars)) . showString "|\n" 
942   | otherwise = id
943
944 showsBars :: [String] -> ShowS
945 showsBars bars
946   = case bars of
947       [] -> id
948       _  -> showString (concat (reverse (tail bars))) . showString node
949
950 node           = "+--"
951 withBar bars   = "|  ":bars
952 withEmpty bars = "   ":bars
953
954 {--------------------------------------------------------------------
955   Assertions
956 --------------------------------------------------------------------}
957 -- | /O(n)/. Test if the internal set structure is valid.
958 valid :: Ord a => Set a -> Bool
959 valid t
960   = balanced t && ordered t && validsize t
961
962 ordered t
963   = bounded (const True) (const True) t
964   where
965     bounded lo hi t
966       = case t of
967           Tip           -> True
968           Bin sz x l r  -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
969
970 balanced :: Set a -> Bool
971 balanced t
972   = case t of
973       Tip           -> True
974       Bin sz x l r  -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
975                        balanced l && balanced r
976
977
978 validsize t
979   = (realsize t == Just (size t))
980   where
981     realsize t
982       = case t of
983           Tip          -> Just 0
984           Bin sz x l r -> case (realsize l,realsize r) of
985                             (Just n,Just m)  | n+m+1 == sz  -> Just sz
986                             other            -> Nothing
987
988 {-
989 {--------------------------------------------------------------------
990   Testing
991 --------------------------------------------------------------------}
992 testTree :: [Int] -> Set Int
993 testTree xs   = fromList xs
994 test1 = testTree [1..20]
995 test2 = testTree [30,29..10]
996 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
997
998 {--------------------------------------------------------------------
999   QuickCheck
1000 --------------------------------------------------------------------}
1001 qcheck prop
1002   = check config prop
1003   where
1004     config = Config
1005       { configMaxTest = 500
1006       , configMaxFail = 5000
1007       , configSize    = \n -> (div n 2 + 3)
1008       , configEvery   = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1009       }
1010
1011
1012 {--------------------------------------------------------------------
1013   Arbitrary, reasonably balanced trees
1014 --------------------------------------------------------------------}
1015 instance (Enum a) => Arbitrary (Set a) where
1016   arbitrary = sized (arbtree 0 maxkey)
1017             where maxkey  = 10000
1018
1019 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
1020 arbtree lo hi n
1021   | n <= 0        = return Tip
1022   | lo >= hi      = return Tip
1023   | otherwise     = do{ i  <- choose (lo,hi)
1024                       ; m  <- choose (1,30)
1025                       ; let (ml,mr)  | m==(1::Int)= (1,2)
1026                                      | m==2       = (2,1)
1027                                      | m==3       = (1,1)
1028                                      | otherwise  = (2,2)
1029                       ; l  <- arbtree lo (i-1) (n `div` ml)
1030                       ; r  <- arbtree (i+1) hi (n `div` mr)
1031                       ; return (bin (toEnum i) l r)
1032                       }  
1033
1034
1035 {--------------------------------------------------------------------
1036   Valid tree's
1037 --------------------------------------------------------------------}
1038 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1039 forValid f
1040   = forAll arbitrary $ \t -> 
1041 --    classify (balanced t) "balanced" $
1042     classify (size t == 0) "empty" $
1043     classify (size t > 0  && size t <= 10) "small" $
1044     classify (size t > 10 && size t <= 64) "medium" $
1045     classify (size t > 64) "large" $
1046     balanced t ==> f t
1047
1048 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1049 forValidIntTree f
1050   = forValid f
1051
1052 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1053 forValidUnitTree f
1054   = forValid f
1055
1056
1057 prop_Valid 
1058   = forValidUnitTree $ \t -> valid t
1059
1060 {--------------------------------------------------------------------
1061   Single, Insert, Delete
1062 --------------------------------------------------------------------}
1063 prop_Single :: Int -> Bool
1064 prop_Single x
1065   = (insert x empty == singleton x)
1066
1067 prop_InsertValid :: Int -> Property
1068 prop_InsertValid k
1069   = forValidUnitTree $ \t -> valid (insert k t)
1070
1071 prop_InsertDelete :: Int -> Set Int -> Property
1072 prop_InsertDelete k t
1073   = not (member k t) ==> delete k (insert k t) == t
1074
1075 prop_DeleteValid :: Int -> Property
1076 prop_DeleteValid k
1077   = forValidUnitTree $ \t -> 
1078     valid (delete k (insert k t))
1079
1080 {--------------------------------------------------------------------
1081   Balance
1082 --------------------------------------------------------------------}
1083 prop_Join :: Int -> Property 
1084 prop_Join x
1085   = forValidUnitTree $ \t ->
1086     let (l,r) = split x t
1087     in valid (join x l r)
1088
1089 prop_Merge :: Int -> Property 
1090 prop_Merge x
1091   = forValidUnitTree $ \t ->
1092     let (l,r) = split x t
1093     in valid (merge l r)
1094
1095
1096 {--------------------------------------------------------------------
1097   Union
1098 --------------------------------------------------------------------}
1099 prop_UnionValid :: Property
1100 prop_UnionValid
1101   = forValidUnitTree $ \t1 ->
1102     forValidUnitTree $ \t2 ->
1103     valid (union t1 t2)
1104
1105 prop_UnionInsert :: Int -> Set Int -> Bool
1106 prop_UnionInsert x t
1107   = union t (singleton x) == insert x t
1108
1109 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1110 prop_UnionAssoc t1 t2 t3
1111   = union t1 (union t2 t3) == union (union t1 t2) t3
1112
1113 prop_UnionComm :: Set Int -> Set Int -> Bool
1114 prop_UnionComm t1 t2
1115   = (union t1 t2 == union t2 t1)
1116
1117
1118 prop_DiffValid
1119   = forValidUnitTree $ \t1 ->
1120     forValidUnitTree $ \t2 ->
1121     valid (difference t1 t2)
1122
1123 prop_Diff :: [Int] -> [Int] -> Bool
1124 prop_Diff xs ys
1125   =  toAscList (difference (fromList xs) (fromList ys))
1126     == List.sort ((List.\\) (nub xs)  (nub ys))
1127
1128 prop_IntValid
1129   = forValidUnitTree $ \t1 ->
1130     forValidUnitTree $ \t2 ->
1131     valid (intersection t1 t2)
1132
1133 prop_Int :: [Int] -> [Int] -> Bool
1134 prop_Int xs ys
1135   =  toAscList (intersection (fromList xs) (fromList ys))
1136     == List.sort (nub ((List.intersect) (xs)  (ys)))
1137
1138 {--------------------------------------------------------------------
1139   Lists
1140 --------------------------------------------------------------------}
1141 prop_Ordered
1142   = forAll (choose (5,100)) $ \n ->
1143     let xs = [0..n::Int]
1144     in fromAscList xs == fromList xs
1145
1146 prop_List :: [Int] -> Bool
1147 prop_List xs
1148   = (sort (nub xs) == toList (fromList xs))
1149 -}