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