1 -----------------------------------------------------------------------------
4 -- Copyright : (c) Daan Leijen 2002
6 -- Maintainer : libraries@haskell.org
7 -- Stability : provisional
8 -- Portability : portable
10 -- An efficient implementation of sets.
12 -- This module is intended to be imported @qualified@, to avoid name
13 -- clashes with "Prelude" functions. eg.
15 -- > import Data.Set as Set
17 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
18 -- trees of /bounded balance/) as described by:
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>.
24 -- * J. Nievergelt and E.M. Reingold,
25 -- \"/Binary search trees of bounded balance/\",
26 -- SIAM journal of computing 2(1), March 1973.
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
33 -----------------------------------------------------------------------------
37 Set -- instance Eq,Ord,Show,Read,Data,Typeable
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
114 import Prelude hiding (filter,foldr,null,map)
115 import qualified Data.List as List
116 import Data.Monoid (Monoid(..))
118 import Data.Foldable (Foldable(foldMap))
123 import List (nub,sort)
124 import qualified List
127 #if __GLASGOW_HASKELL__
129 import Data.Generics.Basics
130 import Data.Generics.Instances
133 {--------------------------------------------------------------------
135 --------------------------------------------------------------------}
138 -- | /O(n+m)/. See 'difference'.
139 (\\) :: Ord a => Set a -> Set a -> Set a
140 m1 \\ m2 = difference m1 m2
142 {--------------------------------------------------------------------
143 Sets are size balanced trees
144 --------------------------------------------------------------------}
145 -- | A set of values @a@.
147 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
151 instance Ord a => Monoid (Set a) where
156 instance Foldable Set where
157 foldMap f Tip = mempty
158 foldMap f (Bin _s k l r) = foldMap f l `mappend` f k `mappend` foldMap f r
160 #if __GLASGOW_HASKELL__
162 {--------------------------------------------------------------------
164 --------------------------------------------------------------------}
166 -- This instance preserves data abstraction at the cost of inefficiency.
167 -- We omit reflection services for the sake of data abstraction.
169 instance (Data a, Ord a) => Data (Set a) where
170 gfoldl f z set = z fromList `f` (toList set)
171 toConstr _ = error "toConstr"
172 gunfold _ _ = error "gunfold"
173 dataTypeOf _ = mkNorepType "Data.Set.Set"
178 {--------------------------------------------------------------------
180 --------------------------------------------------------------------}
181 -- | /O(1)/. Is this the empty set?
182 null :: Set a -> Bool
186 Bin sz x l r -> False
188 -- | /O(1)/. The number of elements in the set.
195 -- | /O(log n)/. Is the element in the set?
196 member :: Ord a => a -> Set a -> Bool
201 -> case compare x y of
206 {--------------------------------------------------------------------
208 --------------------------------------------------------------------}
209 -- | /O(1)/. The empty set.
214 -- | /O(1)/. Create a singleton set.
215 singleton :: a -> Set a
219 {--------------------------------------------------------------------
221 --------------------------------------------------------------------}
222 -- | /O(log n)/. Insert an element in a set.
223 -- If the set already contains an element equal to the given value,
224 -- it is replaced with the new value.
225 insert :: Ord a => a -> Set a -> Set a
230 -> case compare x y of
231 LT -> balance y (insert x l) r
232 GT -> balance y l (insert x r)
236 -- | /O(log n)/. Delete an element from a set.
237 delete :: Ord a => a -> Set a -> Set a
242 -> case compare x y of
243 LT -> balance y (delete x l) r
244 GT -> balance y l (delete x r)
247 {--------------------------------------------------------------------
249 --------------------------------------------------------------------}
250 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
251 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
252 isProperSubsetOf s1 s2
253 = (size s1 < size s2) && (isSubsetOf s1 s2)
256 -- | /O(n+m)/. Is this a subset?
257 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
258 isSubsetOf :: Ord a => Set a -> Set a -> Bool
260 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
262 isSubsetOfX Tip t = True
263 isSubsetOfX t Tip = False
264 isSubsetOfX (Bin _ x l r) t
265 = found && isSubsetOfX l lt && isSubsetOfX r gt
267 (lt,found,gt) = splitMember x t
270 {--------------------------------------------------------------------
272 --------------------------------------------------------------------}
273 -- | /O(log n)/. The minimal element of a set.
274 findMin :: Set a -> a
275 findMin (Bin _ x Tip r) = x
276 findMin (Bin _ x l r) = findMin l
277 findMin Tip = error "Set.findMin: empty set has no minimal element"
279 -- | /O(log n)/. The maximal element of a set.
280 findMax :: Set a -> a
281 findMax (Bin _ x l Tip) = x
282 findMax (Bin _ x l r) = findMax r
283 findMax Tip = error "Set.findMax: empty set has no maximal element"
285 -- | /O(log n)/. Delete the minimal element.
286 deleteMin :: Set a -> Set a
287 deleteMin (Bin _ x Tip r) = r
288 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
291 -- | /O(log n)/. Delete the maximal element.
292 deleteMax :: Set a -> Set a
293 deleteMax (Bin _ x l Tip) = l
294 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
298 {--------------------------------------------------------------------
300 --------------------------------------------------------------------}
301 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
302 unions :: Ord a => [Set a] -> Set a
304 = foldlStrict union empty ts
307 -- | /O(n+m)/. The union of two sets, preferring the first set when
308 -- equal elements are encountered.
309 -- The implementation uses the efficient /hedge-union/ algorithm.
310 -- Hedge-union is more efficient on (bigset `union` smallset).
311 union :: Ord a => Set a -> Set a -> Set a
315 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
316 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
318 hedgeUnion cmplo cmphi t1 Tip
320 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
321 = join x (filterGt cmplo l) (filterLt cmphi r)
322 hedgeUnion cmplo cmphi (Bin _ x l r) t2
323 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
324 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
328 {--------------------------------------------------------------------
330 --------------------------------------------------------------------}
331 -- | /O(n+m)/. Difference of two sets.
332 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
333 difference :: Ord a => Set a -> Set a -> Set a
334 difference Tip t2 = Tip
335 difference t1 Tip = t1
336 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
338 hedgeDiff cmplo cmphi Tip t
340 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
341 = join x (filterGt cmplo l) (filterLt cmphi r)
342 hedgeDiff cmplo cmphi t (Bin _ x l r)
343 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
344 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
348 {--------------------------------------------------------------------
350 --------------------------------------------------------------------}
351 -- | /O(n+m)/. The intersection of two sets.
352 -- Intersection is more efficient on (bigset `intersection` smallset).
353 intersection :: Ord a => Set a -> Set a -> Set a
354 intersection Tip t = Tip
355 intersection t Tip = Tip
357 | size t1 >= size t2 = intersect' t1 t2
358 | otherwise = intersect' t2 t1
360 intersect' Tip t = Tip
361 intersect' t Tip = Tip
362 intersect' t (Bin _ x l r)
363 | found = join x tl tr
364 | otherwise = merge tl tr
366 (lt,found,gt) = splitMember x t
371 {--------------------------------------------------------------------
373 --------------------------------------------------------------------}
374 -- | /O(n)/. Filter all elements that satisfy the predicate.
375 filter :: Ord a => (a -> Bool) -> Set a -> Set a
377 filter p (Bin _ x l r)
378 | p x = join x (filter p l) (filter p r)
379 | otherwise = merge (filter p l) (filter p r)
381 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
382 -- the predicate and one with all elements that don't satisfy the predicate.
384 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
385 partition p Tip = (Tip,Tip)
386 partition p (Bin _ x l r)
387 | p x = (join x l1 r1,merge l2 r2)
388 | otherwise = (merge l1 r1,join x l2 r2)
390 (l1,l2) = partition p l
391 (r1,r2) = partition p r
393 {----------------------------------------------------------------------
395 ----------------------------------------------------------------------}
398 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
400 -- It's worth noting that the size of the result may be smaller if,
401 -- for some @(x,y)@, @x \/= y && f x == f y@
403 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
404 map f = fromList . List.map f . toList
408 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
409 -- /The precondition is not checked./
410 -- Semi-formally, we have:
412 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
413 -- > ==> mapMonotonic f s == map f s
414 -- > where ls = toList s
416 mapMonotonic :: (a->b) -> Set a -> Set b
417 mapMonotonic f Tip = Tip
418 mapMonotonic f (Bin sz x l r) =
419 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
422 {--------------------------------------------------------------------
424 --------------------------------------------------------------------}
425 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
426 fold :: (a -> b -> b) -> b -> Set a -> b
430 -- | /O(n)/. Post-order fold.
431 foldr :: (a -> b -> b) -> b -> Set a -> b
433 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
435 {--------------------------------------------------------------------
437 --------------------------------------------------------------------}
438 -- | /O(n)/. The elements of a set.
439 elems :: Set a -> [a]
443 {--------------------------------------------------------------------
445 --------------------------------------------------------------------}
446 -- | /O(n)/. Convert the set to a list of elements.
447 toList :: Set a -> [a]
451 -- | /O(n)/. Convert the set to an ascending list of elements.
452 toAscList :: Set a -> [a]
457 -- | /O(n*log n)/. Create a set from a list of elements.
458 fromList :: Ord a => [a] -> Set a
460 = foldlStrict ins empty xs
464 {--------------------------------------------------------------------
465 Building trees from ascending/descending lists can be done in linear time.
467 Note that if [xs] is ascending that:
468 fromAscList xs == fromList xs
469 --------------------------------------------------------------------}
470 -- | /O(n)/. Build a set from an ascending list in linear time.
471 -- /The precondition (input list is ascending) is not checked./
472 fromAscList :: Eq a => [a] -> Set a
474 = fromDistinctAscList (combineEq xs)
476 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
481 (x:xx) -> combineEq' x xx
483 combineEq' z [] = [z]
485 | z==x = combineEq' z xs
486 | otherwise = z:combineEq' x xs
489 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
490 -- /The precondition (input list is strictly ascending) is not checked./
491 fromDistinctAscList :: [a] -> Set a
492 fromDistinctAscList xs
493 = build const (length xs) xs
495 -- 1) use continutations so that we use heap space instead of stack space.
496 -- 2) special case for n==5 to build bushier trees.
497 build c 0 xs = c Tip xs
498 build c 5 xs = case xs of
500 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
501 build c n xs = seq nr $ build (buildR nr c) nl xs
506 buildR n c l (x:ys) = build (buildB l x c) n ys
507 buildB l x c r zs = c (bin x l r) zs
509 {--------------------------------------------------------------------
510 Eq converts the set to a list. In a lazy setting, this
511 actually seems one of the faster methods to compare two trees
512 and it is certainly the simplest :-)
513 --------------------------------------------------------------------}
514 instance Eq a => Eq (Set a) where
515 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
517 {--------------------------------------------------------------------
519 --------------------------------------------------------------------}
521 instance Ord a => Ord (Set a) where
522 compare s1 s2 = compare (toAscList s1) (toAscList s2)
524 {--------------------------------------------------------------------
526 --------------------------------------------------------------------}
527 instance Show a => Show (Set a) where
528 showsPrec p xs = showParen (p > 10) $
529 showString "fromList " . shows (toList xs)
531 showSet :: (Show a) => [a] -> ShowS
535 = showChar '{' . shows x . showTail xs
537 showTail [] = showChar '}'
538 showTail (x:xs) = showChar ',' . shows x . showTail xs
540 {--------------------------------------------------------------------
542 --------------------------------------------------------------------}
543 instance (Read a, Ord a) => Read (Set a) where
544 #ifdef __GLASGOW_HASKELL__
545 readPrec = parens $ prec 10 $ do
546 Ident "fromList" <- lexP
550 readListPrec = readListPrecDefault
552 readsPrec p = readParen (p > 10) $ \ r -> do
553 ("fromList",s) <- lex r
555 return (fromList xs,t)
558 {--------------------------------------------------------------------
560 --------------------------------------------------------------------}
562 #include "Typeable.h"
563 INSTANCE_TYPEABLE1(Set,setTc,"Set")
565 {--------------------------------------------------------------------
566 Utility functions that return sub-ranges of the original
567 tree. Some functions take a comparison function as argument to
568 allow comparisons against infinite values. A function [cmplo x]
569 should be read as [compare lo x].
571 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
572 and [cmphi x == GT] for the value [x] of the root.
573 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
574 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
576 [split k t] Returns two trees [l] and [r] where all values
577 in [l] are <[k] and all keys in [r] are >[k].
578 [splitMember k t] Just like [split] but also returns whether [k]
579 was found in the tree.
580 --------------------------------------------------------------------}
582 {--------------------------------------------------------------------
583 [trim lo hi t] trims away all subtrees that surely contain no
584 values between the range [lo] to [hi]. The returned tree is either
585 empty or the key of the root is between @lo@ and @hi@.
586 --------------------------------------------------------------------}
587 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
588 trim cmplo cmphi Tip = Tip
589 trim cmplo cmphi t@(Bin sx x l r)
591 LT -> case cmphi x of
593 le -> trim cmplo cmphi l
594 ge -> trim cmplo cmphi r
596 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
597 trimMemberLo lo cmphi Tip = (False,Tip)
598 trimMemberLo lo cmphi t@(Bin sx x l r)
599 = case compare lo x of
600 LT -> case cmphi x of
601 GT -> (member lo t, t)
602 le -> trimMemberLo lo cmphi l
603 GT -> trimMemberLo lo cmphi r
604 EQ -> (True,trim (compare lo) cmphi r)
607 {--------------------------------------------------------------------
608 [filterGt x t] filter all values >[x] from tree [t]
609 [filterLt x t] filter all values <[x] from tree [t]
610 --------------------------------------------------------------------}
611 filterGt :: (a -> Ordering) -> Set a -> Set a
612 filterGt cmp Tip = Tip
613 filterGt cmp (Bin sx x l r)
615 LT -> join x (filterGt cmp l) r
619 filterLt :: (a -> Ordering) -> Set a -> Set a
620 filterLt cmp Tip = Tip
621 filterLt cmp (Bin sx x l r)
624 GT -> join x l (filterLt cmp r)
628 {--------------------------------------------------------------------
630 --------------------------------------------------------------------}
631 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
632 -- where all elements in @set1@ are lower than @x@ and all elements in
633 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
634 split :: Ord a => a -> Set a -> (Set a,Set a)
635 split x Tip = (Tip,Tip)
636 split x (Bin sy y l r)
637 = case compare x y of
638 LT -> let (lt,gt) = split x l in (lt,join y gt r)
639 GT -> let (lt,gt) = split x r in (join y l lt,gt)
642 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
643 -- element was found in the original set.
644 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
645 splitMember x Tip = (Tip,False,Tip)
646 splitMember x (Bin sy y l r)
647 = case compare x y of
648 LT -> let (lt,found,gt) = splitMember x l in (lt,found,join y gt r)
649 GT -> let (lt,found,gt) = splitMember x r in (join y l lt,found,gt)
652 {--------------------------------------------------------------------
653 Utility functions that maintain the balance properties of the tree.
654 All constructors assume that all values in [l] < [x] and all values
655 in [r] > [x], and that [l] and [r] are valid trees.
657 In order of sophistication:
658 [Bin sz x l r] The type constructor.
659 [bin x l r] Maintains the correct size, assumes that both [l]
660 and [r] are balanced with respect to each other.
661 [balance x l r] Restores the balance and size.
662 Assumes that the original tree was balanced and
663 that [l] or [r] has changed by at most one element.
664 [join x l r] Restores balance and size.
666 Furthermore, we can construct a new tree from two trees. Both operations
667 assume that all values in [l] < all values in [r] and that [l] and [r]
669 [glue l r] Glues [l] and [r] together. Assumes that [l] and
670 [r] are already balanced with respect to each other.
671 [merge l r] Merges two trees and restores balance.
673 Note: in contrast to Adam's paper, we use (<=) comparisons instead
674 of (<) comparisons in [join], [merge] and [balance].
675 Quickcheck (on [difference]) showed that this was necessary in order
676 to maintain the invariants. It is quite unsatisfactory that I haven't
677 been able to find out why this is actually the case! Fortunately, it
678 doesn't hurt to be a bit more conservative.
679 --------------------------------------------------------------------}
681 {--------------------------------------------------------------------
683 --------------------------------------------------------------------}
684 join :: a -> Set a -> Set a -> Set a
685 join x Tip r = insertMin x r
686 join x l Tip = insertMax x l
687 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
688 | delta*sizeL <= sizeR = balance z (join x l lz) rz
689 | delta*sizeR <= sizeL = balance y ly (join x ry r)
690 | otherwise = bin x l r
693 -- insertMin and insertMax don't perform potentially expensive comparisons.
694 insertMax,insertMin :: a -> Set a -> Set a
699 -> balance y l (insertMax x r)
705 -> balance y (insertMin x l) r
707 {--------------------------------------------------------------------
708 [merge l r]: merges two trees.
709 --------------------------------------------------------------------}
710 merge :: Set a -> Set a -> Set a
713 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
714 | delta*sizeL <= sizeR = balance y (merge l ly) ry
715 | delta*sizeR <= sizeL = balance x lx (merge rx r)
716 | otherwise = glue l r
718 {--------------------------------------------------------------------
719 [glue l r]: glues two trees together.
720 Assumes that [l] and [r] are already balanced with respect to each other.
721 --------------------------------------------------------------------}
722 glue :: Set a -> Set a -> Set a
726 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
727 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
730 -- | /O(log n)/. Delete and find the minimal element.
732 -- > deleteFindMin set = (findMin set, deleteMin set)
734 deleteFindMin :: Set a -> (a,Set a)
737 Bin _ x Tip r -> (x,r)
738 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
739 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
741 -- | /O(log n)/. Delete and find the maximal element.
743 -- > deleteFindMax set = (findMax set, deleteMax set)
744 deleteFindMax :: Set a -> (a,Set a)
747 Bin _ x l Tip -> (x,l)
748 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
749 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
752 {--------------------------------------------------------------------
753 [balance x l r] balances two trees with value x.
754 The sizes of the trees should balance after decreasing the
755 size of one of them. (a rotation).
757 [delta] is the maximal relative difference between the sizes of
758 two trees, it corresponds with the [w] in Adams' paper,
759 or equivalently, [1/delta] corresponds with the $\alpha$
760 in Nievergelt's paper. Adams shows that [delta] should
761 be larger than 3.745 in order to garantee that the
762 rotations can always restore balance.
764 [ratio] is the ratio between an outer and inner sibling of the
765 heavier subtree in an unbalanced setting. It determines
766 whether a double or single rotation should be performed
767 to restore balance. It is correspondes with the inverse
768 of $\alpha$ in Adam's article.
771 - [delta] should be larger than 4.646 with a [ratio] of 2.
772 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
774 - A lower [delta] leads to a more 'perfectly' balanced tree.
775 - A higher [delta] performs less rebalancing.
777 - Balancing is automatic for random data and a balancing
778 scheme is only necessary to avoid pathological worst cases.
779 Almost any choice will do in practice
781 - Allthough it seems that a rather large [delta] may perform better
782 than smaller one, measurements have shown that the smallest [delta]
783 of 4 is actually the fastest on a wide range of operations. It
784 especially improves performance on worst-case scenarios like
785 a sequence of ordered insertions.
787 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
788 to decide whether a single or double rotation is needed. Allthough
789 he actually proves that this ratio is needed to maintain the
790 invariants, his implementation uses a (invalid) ratio of 1.
791 He is aware of the problem though since he has put a comment in his
792 original source code that he doesn't care about generating a
793 slightly inbalanced tree since it doesn't seem to matter in practice.
794 However (since we use quickcheck :-) we will stick to strictly balanced
796 --------------------------------------------------------------------}
801 balance :: a -> Set a -> Set a -> Set a
803 | sizeL + sizeR <= 1 = Bin sizeX x l r
804 | sizeR >= delta*sizeL = rotateL x l r
805 | sizeL >= delta*sizeR = rotateR x l r
806 | otherwise = Bin sizeX x l r
810 sizeX = sizeL + sizeR + 1
813 rotateL x l r@(Bin _ _ ly ry)
814 | size ly < ratio*size ry = singleL x l r
815 | otherwise = doubleL x l r
817 rotateR x l@(Bin _ _ ly ry) r
818 | size ry < ratio*size ly = singleR x l r
819 | otherwise = doubleR x l r
822 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
823 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
825 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
826 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
829 {--------------------------------------------------------------------
830 The bin constructor maintains the size of the tree
831 --------------------------------------------------------------------}
832 bin :: a -> Set a -> Set a -> Set a
834 = Bin (size l + size r + 1) x l r
837 {--------------------------------------------------------------------
839 --------------------------------------------------------------------}
843 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
846 {--------------------------------------------------------------------
848 --------------------------------------------------------------------}
849 -- | /O(n)/. Show the tree that implements the set. The tree is shown
850 -- in a compressed, hanging format.
851 showTree :: Show a => Set a -> String
853 = showTreeWith True False s
856 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
857 the tree that implements the set. If @hang@ is
858 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
859 @wide@ is 'True', an extra wide version is shown.
861 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
868 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
879 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
891 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
892 showTreeWith hang wide t
893 | hang = (showsTreeHang wide [] t) ""
894 | otherwise = (showsTree wide [] [] t) ""
896 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
897 showsTree wide lbars rbars t
899 Tip -> showsBars lbars . showString "|\n"
901 -> showsBars lbars . shows x . showString "\n"
903 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
904 showWide wide rbars .
905 showsBars lbars . shows x . showString "\n" .
906 showWide wide lbars .
907 showsTree wide (withEmpty lbars) (withBar lbars) l
909 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
910 showsTreeHang wide bars t
912 Tip -> showsBars bars . showString "|\n"
914 -> showsBars bars . shows x . showString "\n"
916 -> showsBars bars . shows x . showString "\n" .
918 showsTreeHang wide (withBar bars) l .
920 showsTreeHang wide (withEmpty bars) r
924 | wide = showString (concat (reverse bars)) . showString "|\n"
927 showsBars :: [String] -> ShowS
931 _ -> showString (concat (reverse (tail bars))) . showString node
934 withBar bars = "| ":bars
935 withEmpty bars = " ":bars
937 {--------------------------------------------------------------------
939 --------------------------------------------------------------------}
940 -- | /O(n)/. Test if the internal set structure is valid.
941 valid :: Ord a => Set a -> Bool
943 = balanced t && ordered t && validsize t
946 = bounded (const True) (const True) t
951 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
953 balanced :: Set a -> Bool
957 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
958 balanced l && balanced r
962 = (realsize t == Just (size t))
967 Bin sz x l r -> case (realsize l,realsize r) of
968 (Just n,Just m) | n+m+1 == sz -> Just sz
972 {--------------------------------------------------------------------
974 --------------------------------------------------------------------}
975 testTree :: [Int] -> Set Int
976 testTree xs = fromList xs
977 test1 = testTree [1..20]
978 test2 = testTree [30,29..10]
979 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
981 {--------------------------------------------------------------------
983 --------------------------------------------------------------------}
988 { configMaxTest = 500
989 , configMaxFail = 5000
990 , configSize = \n -> (div n 2 + 3)
991 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
995 {--------------------------------------------------------------------
996 Arbitrary, reasonably balanced trees
997 --------------------------------------------------------------------}
998 instance (Enum a) => Arbitrary (Set a) where
999 arbitrary = sized (arbtree 0 maxkey)
1000 where maxkey = 10000
1002 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
1004 | n <= 0 = return Tip
1005 | lo >= hi = return Tip
1006 | otherwise = do{ i <- choose (lo,hi)
1007 ; m <- choose (1,30)
1008 ; let (ml,mr) | m==(1::Int)= (1,2)
1012 ; l <- arbtree lo (i-1) (n `div` ml)
1013 ; r <- arbtree (i+1) hi (n `div` mr)
1014 ; return (bin (toEnum i) l r)
1018 {--------------------------------------------------------------------
1020 --------------------------------------------------------------------}
1021 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1023 = forAll arbitrary $ \t ->
1024 -- classify (balanced t) "balanced" $
1025 classify (size t == 0) "empty" $
1026 classify (size t > 0 && size t <= 10) "small" $
1027 classify (size t > 10 && size t <= 64) "medium" $
1028 classify (size t > 64) "large" $
1031 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1035 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1041 = forValidUnitTree $ \t -> valid t
1043 {--------------------------------------------------------------------
1044 Single, Insert, Delete
1045 --------------------------------------------------------------------}
1046 prop_Single :: Int -> Bool
1048 = (insert x empty == singleton x)
1050 prop_InsertValid :: Int -> Property
1052 = forValidUnitTree $ \t -> valid (insert k t)
1054 prop_InsertDelete :: Int -> Set Int -> Property
1055 prop_InsertDelete k t
1056 = not (member k t) ==> delete k (insert k t) == t
1058 prop_DeleteValid :: Int -> Property
1060 = forValidUnitTree $ \t ->
1061 valid (delete k (insert k t))
1063 {--------------------------------------------------------------------
1065 --------------------------------------------------------------------}
1066 prop_Join :: Int -> Property
1068 = forValidUnitTree $ \t ->
1069 let (l,r) = split x t
1070 in valid (join x l r)
1072 prop_Merge :: Int -> Property
1074 = forValidUnitTree $ \t ->
1075 let (l,r) = split x t
1076 in valid (merge l r)
1079 {--------------------------------------------------------------------
1081 --------------------------------------------------------------------}
1082 prop_UnionValid :: Property
1084 = forValidUnitTree $ \t1 ->
1085 forValidUnitTree $ \t2 ->
1088 prop_UnionInsert :: Int -> Set Int -> Bool
1089 prop_UnionInsert x t
1090 = union t (singleton x) == insert x t
1092 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1093 prop_UnionAssoc t1 t2 t3
1094 = union t1 (union t2 t3) == union (union t1 t2) t3
1096 prop_UnionComm :: Set Int -> Set Int -> Bool
1097 prop_UnionComm t1 t2
1098 = (union t1 t2 == union t2 t1)
1102 = forValidUnitTree $ \t1 ->
1103 forValidUnitTree $ \t2 ->
1104 valid (difference t1 t2)
1106 prop_Diff :: [Int] -> [Int] -> Bool
1108 = toAscList (difference (fromList xs) (fromList ys))
1109 == List.sort ((List.\\) (nub xs) (nub ys))
1112 = forValidUnitTree $ \t1 ->
1113 forValidUnitTree $ \t2 ->
1114 valid (intersection t1 t2)
1116 prop_Int :: [Int] -> [Int] -> Bool
1118 = toAscList (intersection (fromList xs) (fromList ys))
1119 == List.sort (nub ((List.intersect) (xs) (ys)))
1121 {--------------------------------------------------------------------
1123 --------------------------------------------------------------------}
1125 = forAll (choose (5,100)) $ \n ->
1126 let xs = [0..n::Int]
1127 in fromAscList xs == fromList xs
1129 prop_List :: [Int] -> Bool
1131 = (sort (nub xs) == toList (fromList xs))
1134 {--------------------------------------------------------------------
1135 Old Data.Set compatibility interface
1136 --------------------------------------------------------------------}
1138 {-# DEPRECATED emptySet "Use empty instead" #-}
1139 -- | Obsolete equivalent of 'empty'.
1143 {-# DEPRECATED mkSet "Use fromList instead" #-}
1144 -- | Obsolete equivalent of 'fromList'.
1145 mkSet :: Ord a => [a] -> Set a
1148 {-# DEPRECATED setToList "Use elems instead." #-}
1149 -- | Obsolete equivalent of 'elems'.
1150 setToList :: Set a -> [a]
1153 {-# DEPRECATED unitSet "Use singleton instead." #-}
1154 -- | Obsolete equivalent of 'singleton'.
1155 unitSet :: a -> Set a
1158 {-# DEPRECATED elementOf "Use member instead." #-}
1159 -- | Obsolete equivalent of 'member'.
1160 elementOf :: Ord a => a -> Set a -> Bool
1163 {-# DEPRECATED isEmptySet "Use null instead." #-}
1164 -- | Obsolete equivalent of 'null'.
1165 isEmptySet :: Set a -> Bool
1168 {-# DEPRECATED cardinality "Use size instead." #-}
1169 -- | Obsolete equivalent of 'size'.
1170 cardinality :: Set a -> Int
1173 {-# DEPRECATED unionManySets "Use unions instead." #-}
1174 -- | Obsolete equivalent of 'unions'.
1175 unionManySets :: Ord a => [Set a] -> Set a
1176 unionManySets = unions
1178 {-# DEPRECATED minusSet "Use difference instead." #-}
1179 -- | Obsolete equivalent of 'difference'.
1180 minusSet :: Ord a => Set a -> Set a -> Set a
1181 minusSet = difference
1183 {-# DEPRECATED mapSet "Use map instead." #-}
1184 -- | Obsolete equivalent of 'map'.
1185 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1188 {-# DEPRECATED intersect "Use intersection instead." #-}
1189 -- | Obsolete equivalent of 'intersection'.
1190 intersect :: Ord a => Set a -> Set a -> Set a
1191 intersect = intersection
1193 {-# DEPRECATED addToSet "Use 'flip insert' instead." #-}
1194 -- | Obsolete equivalent of @'flip' 'insert'@.
1195 addToSet :: Ord a => Set a -> a -> Set a
1196 addToSet = flip insert
1198 {-# DEPRECATED delFromSet "Use `flip delete' instead." #-}
1199 -- | Obsolete equivalent of @'flip' 'delete'@.
1200 delFromSet :: Ord a => Set a -> a -> Set a
1201 delFromSet = flip delete