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(..))
122 import List (nub,sort)
123 import qualified List
126 #if __GLASGOW_HASKELL__
128 import Data.Generics.Basics
129 import Data.Generics.Instances
132 {--------------------------------------------------------------------
134 --------------------------------------------------------------------}
137 -- | /O(n+m)/. See 'difference'.
138 (\\) :: Ord a => Set a -> Set a -> Set a
139 m1 \\ m2 = difference m1 m2
141 {--------------------------------------------------------------------
142 Sets are size balanced trees
143 --------------------------------------------------------------------}
144 -- | A set of values @a@.
146 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
150 instance Ord a => Monoid (Set a) where
155 #if __GLASGOW_HASKELL__
157 {--------------------------------------------------------------------
159 --------------------------------------------------------------------}
161 -- This instance preserves data abstraction at the cost of inefficiency.
162 -- We omit reflection services for the sake of data abstraction.
164 instance (Data a, Ord a) => Data (Set a) where
165 gfoldl f z set = z fromList `f` (toList set)
166 toConstr _ = error "toConstr"
167 gunfold _ _ = error "gunfold"
168 dataTypeOf _ = mkNorepType "Data.Set.Set"
172 {--------------------------------------------------------------------
174 --------------------------------------------------------------------}
175 -- | /O(1)/. Is this the empty set?
176 null :: Set a -> Bool
180 Bin sz x l r -> False
182 -- | /O(1)/. The number of elements in the set.
189 -- | /O(log n)/. Is the element in the set?
190 member :: Ord a => a -> Set a -> Bool
195 -> case compare x y of
200 {--------------------------------------------------------------------
202 --------------------------------------------------------------------}
203 -- | /O(1)/. The empty set.
208 -- | /O(1)/. Create a singleton set.
209 singleton :: a -> Set a
213 {--------------------------------------------------------------------
215 --------------------------------------------------------------------}
216 -- | /O(log n)/. Insert an element in a set.
217 -- If the set already contains an element equal to the given value,
218 -- it is replaced with the new value.
219 insert :: Ord a => a -> Set a -> Set a
224 -> case compare x y of
225 LT -> balance y (insert x l) r
226 GT -> balance y l (insert x r)
230 -- | /O(log n)/. Delete an element from a set.
231 delete :: Ord a => a -> Set a -> Set a
236 -> case compare x y of
237 LT -> balance y (delete x l) r
238 GT -> balance y l (delete x r)
241 {--------------------------------------------------------------------
243 --------------------------------------------------------------------}
244 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
245 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
246 isProperSubsetOf s1 s2
247 = (size s1 < size s2) && (isSubsetOf s1 s2)
250 -- | /O(n+m)/. Is this a subset?
251 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
252 isSubsetOf :: Ord a => Set a -> Set a -> Bool
254 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
256 isSubsetOfX Tip t = True
257 isSubsetOfX t Tip = False
258 isSubsetOfX (Bin _ x l r) t
259 = found && isSubsetOfX l lt && isSubsetOfX r gt
261 (lt,found,gt) = splitMember x t
264 {--------------------------------------------------------------------
266 --------------------------------------------------------------------}
267 -- | /O(log n)/. The minimal element of a set.
268 findMin :: Set a -> a
269 findMin (Bin _ x Tip r) = x
270 findMin (Bin _ x l r) = findMin l
271 findMin Tip = error "Set.findMin: empty set has no minimal element"
273 -- | /O(log n)/. The maximal element of a set.
274 findMax :: Set a -> a
275 findMax (Bin _ x l Tip) = x
276 findMax (Bin _ x l r) = findMax r
277 findMax Tip = error "Set.findMax: empty set has no maximal element"
279 -- | /O(log n)/. Delete the minimal element.
280 deleteMin :: Set a -> Set a
281 deleteMin (Bin _ x Tip r) = r
282 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
285 -- | /O(log n)/. Delete the maximal element.
286 deleteMax :: Set a -> Set a
287 deleteMax (Bin _ x l Tip) = l
288 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
292 {--------------------------------------------------------------------
294 --------------------------------------------------------------------}
295 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
296 unions :: Ord a => [Set a] -> Set a
298 = foldlStrict union empty ts
301 -- | /O(n+m)/. The union of two sets, preferring the first set when
302 -- equal elements are encountered.
303 -- The implementation uses the efficient /hedge-union/ algorithm.
304 -- Hedge-union is more efficient on (bigset `union` smallset).
305 union :: Ord a => Set a -> Set a -> Set a
309 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
310 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
312 hedgeUnion cmplo cmphi t1 Tip
314 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
315 = join x (filterGt cmplo l) (filterLt cmphi r)
316 hedgeUnion cmplo cmphi (Bin _ x l r) t2
317 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
318 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
322 {--------------------------------------------------------------------
324 --------------------------------------------------------------------}
325 -- | /O(n+m)/. Difference of two sets.
326 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
327 difference :: Ord a => Set a -> Set a -> Set a
328 difference Tip t2 = Tip
329 difference t1 Tip = t1
330 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
332 hedgeDiff cmplo cmphi Tip t
334 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
335 = join x (filterGt cmplo l) (filterLt cmphi r)
336 hedgeDiff cmplo cmphi t (Bin _ x l r)
337 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
338 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
342 {--------------------------------------------------------------------
344 --------------------------------------------------------------------}
345 -- | /O(n+m)/. The intersection of two sets.
346 -- Intersection is more efficient on (bigset `intersection` smallset).
347 intersection :: Ord a => Set a -> Set a -> Set a
348 intersection Tip t = Tip
349 intersection t Tip = Tip
351 | size t1 >= size t2 = intersect' t1 t2
352 | otherwise = intersect' t2 t1
354 intersect' Tip t = Tip
355 intersect' t Tip = Tip
356 intersect' t (Bin _ x l r)
357 | found = join x tl tr
358 | otherwise = merge tl tr
360 (lt,found,gt) = splitMember x t
365 {--------------------------------------------------------------------
367 --------------------------------------------------------------------}
368 -- | /O(n)/. Filter all elements that satisfy the predicate.
369 filter :: Ord a => (a -> Bool) -> Set a -> Set a
371 filter p (Bin _ x l r)
372 | p x = join x (filter p l) (filter p r)
373 | otherwise = merge (filter p l) (filter p r)
375 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
376 -- the predicate and one with all elements that don't satisfy the predicate.
378 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
379 partition p Tip = (Tip,Tip)
380 partition p (Bin _ x l r)
381 | p x = (join x l1 r1,merge l2 r2)
382 | otherwise = (merge l1 r1,join x l2 r2)
384 (l1,l2) = partition p l
385 (r1,r2) = partition p r
387 {----------------------------------------------------------------------
389 ----------------------------------------------------------------------}
392 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
394 -- It's worth noting that the size of the result may be smaller if,
395 -- for some @(x,y)@, @x \/= y && f x == f y@
397 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
398 map f = fromList . List.map f . toList
402 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
403 -- /The precondition is not checked./
404 -- Semi-formally, we have:
406 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
407 -- > ==> mapMonotonic f s == map f s
408 -- > where ls = toList s
410 mapMonotonic :: (a->b) -> Set a -> Set b
411 mapMonotonic f Tip = Tip
412 mapMonotonic f (Bin sz x l r) =
413 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
416 {--------------------------------------------------------------------
418 --------------------------------------------------------------------}
419 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
420 fold :: (a -> b -> b) -> b -> Set a -> b
424 -- | /O(n)/. Post-order fold.
425 foldr :: (a -> b -> b) -> b -> Set a -> b
427 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
429 {--------------------------------------------------------------------
431 --------------------------------------------------------------------}
432 -- | /O(n)/. The elements of a set.
433 elems :: Set a -> [a]
437 {--------------------------------------------------------------------
439 --------------------------------------------------------------------}
440 -- | /O(n)/. Convert the set to a list of elements.
441 toList :: Set a -> [a]
445 -- | /O(n)/. Convert the set to an ascending list of elements.
446 toAscList :: Set a -> [a]
451 -- | /O(n*log n)/. Create a set from a list of elements.
452 fromList :: Ord a => [a] -> Set a
454 = foldlStrict ins empty xs
458 {--------------------------------------------------------------------
459 Building trees from ascending/descending lists can be done in linear time.
461 Note that if [xs] is ascending that:
462 fromAscList xs == fromList xs
463 --------------------------------------------------------------------}
464 -- | /O(n)/. Build a set from an ascending list in linear time.
465 -- /The precondition (input list is ascending) is not checked./
466 fromAscList :: Eq a => [a] -> Set a
468 = fromDistinctAscList (combineEq xs)
470 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
475 (x:xx) -> combineEq' x xx
477 combineEq' z [] = [z]
479 | z==x = combineEq' z xs
480 | otherwise = z:combineEq' x xs
483 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
484 -- /The precondition (input list is strictly ascending) is not checked./
485 fromDistinctAscList :: [a] -> Set a
486 fromDistinctAscList xs
487 = build const (length xs) xs
489 -- 1) use continutations so that we use heap space instead of stack space.
490 -- 2) special case for n==5 to build bushier trees.
491 build c 0 xs = c Tip xs
492 build c 5 xs = case xs of
494 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
495 build c n xs = seq nr $ build (buildR nr c) nl xs
500 buildR n c l (x:ys) = build (buildB l x c) n ys
501 buildB l x c r zs = c (bin x l r) zs
503 {--------------------------------------------------------------------
504 Eq converts the set to a list. In a lazy setting, this
505 actually seems one of the faster methods to compare two trees
506 and it is certainly the simplest :-)
507 --------------------------------------------------------------------}
508 instance Eq a => Eq (Set a) where
509 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
511 {--------------------------------------------------------------------
513 --------------------------------------------------------------------}
515 instance Ord a => Ord (Set a) where
516 compare s1 s2 = compare (toAscList s1) (toAscList s2)
518 {--------------------------------------------------------------------
520 --------------------------------------------------------------------}
521 instance Show a => Show (Set a) where
522 showsPrec p xs = showParen (p > 10) $
523 showString "fromList " . shows (toList xs)
525 showSet :: (Show a) => [a] -> ShowS
529 = showChar '{' . shows x . showTail xs
531 showTail [] = showChar '}'
532 showTail (x:xs) = showChar ',' . shows x . showTail xs
534 {--------------------------------------------------------------------
536 --------------------------------------------------------------------}
537 instance (Read a, Ord a) => Read (Set a) where
538 #ifdef __GLASGOW_HASKELL__
539 readPrec = parens $ prec 10 $ do
540 Ident "fromList" <- lexP
544 readListPrec = readListPrecDefault
546 readsPrec p = readParen (p > 10) $ \ r -> do
547 ("fromList",s) <- lex r
549 return (fromList xs,t)
552 {--------------------------------------------------------------------
554 --------------------------------------------------------------------}
556 #include "Typeable.h"
557 INSTANCE_TYPEABLE1(Set,setTc,"Set")
559 {--------------------------------------------------------------------
560 Utility functions that return sub-ranges of the original
561 tree. Some functions take a comparison function as argument to
562 allow comparisons against infinite values. A function [cmplo x]
563 should be read as [compare lo x].
565 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
566 and [cmphi x == GT] for the value [x] of the root.
567 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
568 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
570 [split k t] Returns two trees [l] and [r] where all values
571 in [l] are <[k] and all keys in [r] are >[k].
572 [splitMember k t] Just like [split] but also returns whether [k]
573 was found in the tree.
574 --------------------------------------------------------------------}
576 {--------------------------------------------------------------------
577 [trim lo hi t] trims away all subtrees that surely contain no
578 values between the range [lo] to [hi]. The returned tree is either
579 empty or the key of the root is between @lo@ and @hi@.
580 --------------------------------------------------------------------}
581 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
582 trim cmplo cmphi Tip = Tip
583 trim cmplo cmphi t@(Bin sx x l r)
585 LT -> case cmphi x of
587 le -> trim cmplo cmphi l
588 ge -> trim cmplo cmphi r
590 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
591 trimMemberLo lo cmphi Tip = (False,Tip)
592 trimMemberLo lo cmphi t@(Bin sx x l r)
593 = case compare lo x of
594 LT -> case cmphi x of
595 GT -> (member lo t, t)
596 le -> trimMemberLo lo cmphi l
597 GT -> trimMemberLo lo cmphi r
598 EQ -> (True,trim (compare lo) cmphi r)
601 {--------------------------------------------------------------------
602 [filterGt x t] filter all values >[x] from tree [t]
603 [filterLt x t] filter all values <[x] from tree [t]
604 --------------------------------------------------------------------}
605 filterGt :: (a -> Ordering) -> Set a -> Set a
606 filterGt cmp Tip = Tip
607 filterGt cmp (Bin sx x l r)
609 LT -> join x (filterGt cmp l) r
613 filterLt :: (a -> Ordering) -> Set a -> Set a
614 filterLt cmp Tip = Tip
615 filterLt cmp (Bin sx x l r)
618 GT -> join x l (filterLt cmp r)
622 {--------------------------------------------------------------------
624 --------------------------------------------------------------------}
625 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
626 -- where all elements in @set1@ are lower than @x@ and all elements in
627 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
628 split :: Ord a => a -> Set a -> (Set a,Set a)
629 split x Tip = (Tip,Tip)
630 split x (Bin sy y l r)
631 = case compare x y of
632 LT -> let (lt,gt) = split x l in (lt,join y gt r)
633 GT -> let (lt,gt) = split x r in (join y l lt,gt)
636 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
637 -- element was found in the original set.
638 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
639 splitMember x Tip = (Tip,False,Tip)
640 splitMember x (Bin sy y l r)
641 = case compare x y of
642 LT -> let (lt,found,gt) = splitMember x l in (lt,found,join y gt r)
643 GT -> let (lt,found,gt) = splitMember x r in (join y l lt,found,gt)
646 {--------------------------------------------------------------------
647 Utility functions that maintain the balance properties of the tree.
648 All constructors assume that all values in [l] < [x] and all values
649 in [r] > [x], and that [l] and [r] are valid trees.
651 In order of sophistication:
652 [Bin sz x l r] The type constructor.
653 [bin x l r] Maintains the correct size, assumes that both [l]
654 and [r] are balanced with respect to each other.
655 [balance x l r] Restores the balance and size.
656 Assumes that the original tree was balanced and
657 that [l] or [r] has changed by at most one element.
658 [join x l r] Restores balance and size.
660 Furthermore, we can construct a new tree from two trees. Both operations
661 assume that all values in [l] < all values in [r] and that [l] and [r]
663 [glue l r] Glues [l] and [r] together. Assumes that [l] and
664 [r] are already balanced with respect to each other.
665 [merge l r] Merges two trees and restores balance.
667 Note: in contrast to Adam's paper, we use (<=) comparisons instead
668 of (<) comparisons in [join], [merge] and [balance].
669 Quickcheck (on [difference]) showed that this was necessary in order
670 to maintain the invariants. It is quite unsatisfactory that I haven't
671 been able to find out why this is actually the case! Fortunately, it
672 doesn't hurt to be a bit more conservative.
673 --------------------------------------------------------------------}
675 {--------------------------------------------------------------------
677 --------------------------------------------------------------------}
678 join :: a -> Set a -> Set a -> Set a
679 join x Tip r = insertMin x r
680 join x l Tip = insertMax x l
681 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
682 | delta*sizeL <= sizeR = balance z (join x l lz) rz
683 | delta*sizeR <= sizeL = balance y ly (join x ry r)
684 | otherwise = bin x l r
687 -- insertMin and insertMax don't perform potentially expensive comparisons.
688 insertMax,insertMin :: a -> Set a -> Set a
693 -> balance y l (insertMax x r)
699 -> balance y (insertMin x l) r
701 {--------------------------------------------------------------------
702 [merge l r]: merges two trees.
703 --------------------------------------------------------------------}
704 merge :: Set a -> Set a -> Set a
707 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
708 | delta*sizeL <= sizeR = balance y (merge l ly) ry
709 | delta*sizeR <= sizeL = balance x lx (merge rx r)
710 | otherwise = glue l r
712 {--------------------------------------------------------------------
713 [glue l r]: glues two trees together.
714 Assumes that [l] and [r] are already balanced with respect to each other.
715 --------------------------------------------------------------------}
716 glue :: Set a -> Set a -> Set a
720 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
721 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
724 -- | /O(log n)/. Delete and find the minimal element.
726 -- > deleteFindMin set = (findMin set, deleteMin set)
728 deleteFindMin :: Set a -> (a,Set a)
731 Bin _ x Tip r -> (x,r)
732 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
733 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
735 -- | /O(log n)/. Delete and find the maximal element.
737 -- > deleteFindMax set = (findMax set, deleteMax set)
738 deleteFindMax :: Set a -> (a,Set a)
741 Bin _ x l Tip -> (x,l)
742 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
743 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
746 {--------------------------------------------------------------------
747 [balance x l r] balances two trees with value x.
748 The sizes of the trees should balance after decreasing the
749 size of one of them. (a rotation).
751 [delta] is the maximal relative difference between the sizes of
752 two trees, it corresponds with the [w] in Adams' paper,
753 or equivalently, [1/delta] corresponds with the $\alpha$
754 in Nievergelt's paper. Adams shows that [delta] should
755 be larger than 3.745 in order to garantee that the
756 rotations can always restore balance.
758 [ratio] is the ratio between an outer and inner sibling of the
759 heavier subtree in an unbalanced setting. It determines
760 whether a double or single rotation should be performed
761 to restore balance. It is correspondes with the inverse
762 of $\alpha$ in Adam's article.
765 - [delta] should be larger than 4.646 with a [ratio] of 2.
766 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
768 - A lower [delta] leads to a more 'perfectly' balanced tree.
769 - A higher [delta] performs less rebalancing.
771 - Balancing is automatic for random data and a balancing
772 scheme is only necessary to avoid pathological worst cases.
773 Almost any choice will do in practice
775 - Allthough it seems that a rather large [delta] may perform better
776 than smaller one, measurements have shown that the smallest [delta]
777 of 4 is actually the fastest on a wide range of operations. It
778 especially improves performance on worst-case scenarios like
779 a sequence of ordered insertions.
781 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
782 to decide whether a single or double rotation is needed. Allthough
783 he actually proves that this ratio is needed to maintain the
784 invariants, his implementation uses a (invalid) ratio of 1.
785 He is aware of the problem though since he has put a comment in his
786 original source code that he doesn't care about generating a
787 slightly inbalanced tree since it doesn't seem to matter in practice.
788 However (since we use quickcheck :-) we will stick to strictly balanced
790 --------------------------------------------------------------------}
795 balance :: a -> Set a -> Set a -> Set a
797 | sizeL + sizeR <= 1 = Bin sizeX x l r
798 | sizeR >= delta*sizeL = rotateL x l r
799 | sizeL >= delta*sizeR = rotateR x l r
800 | otherwise = Bin sizeX x l r
804 sizeX = sizeL + sizeR + 1
807 rotateL x l r@(Bin _ _ ly ry)
808 | size ly < ratio*size ry = singleL x l r
809 | otherwise = doubleL x l r
811 rotateR x l@(Bin _ _ ly ry) r
812 | size ry < ratio*size ly = singleR x l r
813 | otherwise = doubleR x l r
816 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
817 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
819 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
820 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
823 {--------------------------------------------------------------------
824 The bin constructor maintains the size of the tree
825 --------------------------------------------------------------------}
826 bin :: a -> Set a -> Set a -> Set a
828 = Bin (size l + size r + 1) x l r
831 {--------------------------------------------------------------------
833 --------------------------------------------------------------------}
837 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
840 {--------------------------------------------------------------------
842 --------------------------------------------------------------------}
843 -- | /O(n)/. Show the tree that implements the set. The tree is shown
844 -- in a compressed, hanging format.
845 showTree :: Show a => Set a -> String
847 = showTreeWith True False s
850 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
851 the tree that implements the set. If @hang@ is
852 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
853 @wide@ is 'True', an extra wide version is shown.
855 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
862 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
873 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
885 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
886 showTreeWith hang wide t
887 | hang = (showsTreeHang wide [] t) ""
888 | otherwise = (showsTree wide [] [] t) ""
890 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
891 showsTree wide lbars rbars t
893 Tip -> showsBars lbars . showString "|\n"
895 -> showsBars lbars . shows x . showString "\n"
897 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
898 showWide wide rbars .
899 showsBars lbars . shows x . showString "\n" .
900 showWide wide lbars .
901 showsTree wide (withEmpty lbars) (withBar lbars) l
903 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
904 showsTreeHang wide bars t
906 Tip -> showsBars bars . showString "|\n"
908 -> showsBars bars . shows x . showString "\n"
910 -> showsBars bars . shows x . showString "\n" .
912 showsTreeHang wide (withBar bars) l .
914 showsTreeHang wide (withEmpty bars) r
918 | wide = showString (concat (reverse bars)) . showString "|\n"
921 showsBars :: [String] -> ShowS
925 _ -> showString (concat (reverse (tail bars))) . showString node
928 withBar bars = "| ":bars
929 withEmpty bars = " ":bars
931 {--------------------------------------------------------------------
933 --------------------------------------------------------------------}
934 -- | /O(n)/. Test if the internal set structure is valid.
935 valid :: Ord a => Set a -> Bool
937 = balanced t && ordered t && validsize t
940 = bounded (const True) (const True) t
945 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
947 balanced :: Set a -> Bool
951 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
952 balanced l && balanced r
956 = (realsize t == Just (size t))
961 Bin sz x l r -> case (realsize l,realsize r) of
962 (Just n,Just m) | n+m+1 == sz -> Just sz
966 {--------------------------------------------------------------------
968 --------------------------------------------------------------------}
969 testTree :: [Int] -> Set Int
970 testTree xs = fromList xs
971 test1 = testTree [1..20]
972 test2 = testTree [30,29..10]
973 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
975 {--------------------------------------------------------------------
977 --------------------------------------------------------------------}
982 { configMaxTest = 500
983 , configMaxFail = 5000
984 , configSize = \n -> (div n 2 + 3)
985 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
989 {--------------------------------------------------------------------
990 Arbitrary, reasonably balanced trees
991 --------------------------------------------------------------------}
992 instance (Enum a) => Arbitrary (Set a) where
993 arbitrary = sized (arbtree 0 maxkey)
996 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
998 | n <= 0 = return Tip
999 | lo >= hi = return Tip
1000 | otherwise = do{ i <- choose (lo,hi)
1001 ; m <- choose (1,30)
1002 ; let (ml,mr) | m==(1::Int)= (1,2)
1006 ; l <- arbtree lo (i-1) (n `div` ml)
1007 ; r <- arbtree (i+1) hi (n `div` mr)
1008 ; return (bin (toEnum i) l r)
1012 {--------------------------------------------------------------------
1014 --------------------------------------------------------------------}
1015 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1017 = forAll arbitrary $ \t ->
1018 -- classify (balanced t) "balanced" $
1019 classify (size t == 0) "empty" $
1020 classify (size t > 0 && size t <= 10) "small" $
1021 classify (size t > 10 && size t <= 64) "medium" $
1022 classify (size t > 64) "large" $
1025 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1029 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1035 = forValidUnitTree $ \t -> valid t
1037 {--------------------------------------------------------------------
1038 Single, Insert, Delete
1039 --------------------------------------------------------------------}
1040 prop_Single :: Int -> Bool
1042 = (insert x empty == singleton x)
1044 prop_InsertValid :: Int -> Property
1046 = forValidUnitTree $ \t -> valid (insert k t)
1048 prop_InsertDelete :: Int -> Set Int -> Property
1049 prop_InsertDelete k t
1050 = not (member k t) ==> delete k (insert k t) == t
1052 prop_DeleteValid :: Int -> Property
1054 = forValidUnitTree $ \t ->
1055 valid (delete k (insert k t))
1057 {--------------------------------------------------------------------
1059 --------------------------------------------------------------------}
1060 prop_Join :: Int -> Property
1062 = forValidUnitTree $ \t ->
1063 let (l,r) = split x t
1064 in valid (join x l r)
1066 prop_Merge :: Int -> Property
1068 = forValidUnitTree $ \t ->
1069 let (l,r) = split x t
1070 in valid (merge l r)
1073 {--------------------------------------------------------------------
1075 --------------------------------------------------------------------}
1076 prop_UnionValid :: Property
1078 = forValidUnitTree $ \t1 ->
1079 forValidUnitTree $ \t2 ->
1082 prop_UnionInsert :: Int -> Set Int -> Bool
1083 prop_UnionInsert x t
1084 = union t (singleton x) == insert x t
1086 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1087 prop_UnionAssoc t1 t2 t3
1088 = union t1 (union t2 t3) == union (union t1 t2) t3
1090 prop_UnionComm :: Set Int -> Set Int -> Bool
1091 prop_UnionComm t1 t2
1092 = (union t1 t2 == union t2 t1)
1096 = forValidUnitTree $ \t1 ->
1097 forValidUnitTree $ \t2 ->
1098 valid (difference t1 t2)
1100 prop_Diff :: [Int] -> [Int] -> Bool
1102 = toAscList (difference (fromList xs) (fromList ys))
1103 == List.sort ((List.\\) (nub xs) (nub ys))
1106 = forValidUnitTree $ \t1 ->
1107 forValidUnitTree $ \t2 ->
1108 valid (intersection t1 t2)
1110 prop_Int :: [Int] -> [Int] -> Bool
1112 = toAscList (intersection (fromList xs) (fromList ys))
1113 == List.sort (nub ((List.intersect) (xs) (ys)))
1115 {--------------------------------------------------------------------
1117 --------------------------------------------------------------------}
1119 = forAll (choose (5,100)) $ \n ->
1120 let xs = [0..n::Int]
1121 in fromAscList xs == fromList xs
1123 prop_List :: [Int] -> Bool
1125 = (sort (nub xs) == toList (fromList xs))
1128 {--------------------------------------------------------------------
1129 Old Data.Set compatibility interface
1130 --------------------------------------------------------------------}
1132 {-# DEPRECATED emptySet "Use empty instead" #-}
1133 -- | Obsolete equivalent of 'empty'.
1137 {-# DEPRECATED mkSet "Use fromList instead" #-}
1138 -- | Obsolete equivalent of 'fromList'.
1139 mkSet :: Ord a => [a] -> Set a
1142 {-# DEPRECATED setToList "Use elems instead." #-}
1143 -- | Obsolete equivalent of 'elems'.
1144 setToList :: Set a -> [a]
1147 {-# DEPRECATED unitSet "Use singleton instead." #-}
1148 -- | Obsolete equivalent of 'singleton'.
1149 unitSet :: a -> Set a
1152 {-# DEPRECATED elementOf "Use member instead." #-}
1153 -- | Obsolete equivalent of 'member'.
1154 elementOf :: Ord a => a -> Set a -> Bool
1157 {-# DEPRECATED isEmptySet "Use null instead." #-}
1158 -- | Obsolete equivalent of 'null'.
1159 isEmptySet :: Set a -> Bool
1162 {-# DEPRECATED cardinality "Use size instead." #-}
1163 -- | Obsolete equivalent of 'size'.
1164 cardinality :: Set a -> Int
1167 {-# DEPRECATED unionManySets "Use unions instead." #-}
1168 -- | Obsolete equivalent of 'unions'.
1169 unionManySets :: Ord a => [Set a] -> Set a
1170 unionManySets = unions
1172 {-# DEPRECATED minusSet "Use difference instead." #-}
1173 -- | Obsolete equivalent of 'difference'.
1174 minusSet :: Ord a => Set a -> Set a -> Set a
1175 minusSet = difference
1177 {-# DEPRECATED mapSet "Use map instead." #-}
1178 -- | Obsolete equivalent of 'map'.
1179 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1182 {-# DEPRECATED intersect "Use intersection instead." #-}
1183 -- | Obsolete equivalent of 'intersection'.
1184 intersect :: Ord a => Set a -> Set a -> Set a
1185 intersect = intersection
1187 {-# DEPRECATED addToSet "Use 'flip insert' instead." #-}
1188 -- | Obsolete equivalent of @'flip' 'insert'@.
1189 addToSet :: Ord a => Set a -> a -> Set a
1190 addToSet = flip insert
1192 {-# DEPRECATED delFromSet "Use `flip delete' instead." #-}
1193 -- | Obsolete equivalent of @'flip' 'delete'@.
1194 delFromSet :: Ord a => Set a -> a -> Set a
1195 delFromSet = flip delete