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