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