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,Show
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
121 import List (nub,sort)
122 import qualified List
125 #if __GLASGOW_HASKELL__
126 import Data.Generics.Basics
127 import Data.Generics.Instances
130 {--------------------------------------------------------------------
132 --------------------------------------------------------------------}
135 -- | /O(n+m)/. See 'difference'.
136 (\\) :: Ord a => Set a -> Set a -> Set a
137 m1 \\ m2 = difference m1 m2
139 {--------------------------------------------------------------------
140 Sets are size balanced trees
141 --------------------------------------------------------------------}
142 -- | A set of values @a@.
144 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
148 #if __GLASGOW_HASKELL__
150 {--------------------------------------------------------------------
152 --------------------------------------------------------------------}
154 -- This instance preserves data abstraction at the cost of inefficiency.
155 -- We omit reflection services for the sake of data abstraction.
157 instance (Data a, Ord a) => Data (Set a) where
158 gfoldl f z set = z fromList `f` (toList set)
159 toConstr _ = error "toConstr"
160 gunfold _ _ = error "gunfold"
161 dataTypeOf _ = mkNorepType "Data.Set.Set"
165 {--------------------------------------------------------------------
167 --------------------------------------------------------------------}
168 -- | /O(1)/. Is this the empty set?
169 null :: Set a -> Bool
173 Bin sz x l r -> False
175 -- | /O(1)/. The number of elements in the set.
182 -- | /O(log n)/. Is the element in the set?
183 member :: Ord a => a -> Set a -> Bool
188 -> case compare x y of
193 {--------------------------------------------------------------------
195 --------------------------------------------------------------------}
196 -- | /O(1)/. The empty set.
201 -- | /O(1)/. Create a singleton set.
202 singleton :: a -> Set a
206 {--------------------------------------------------------------------
208 --------------------------------------------------------------------}
209 -- | /O(log n)/. Insert an element in a set.
210 -- If the set already contains an element equal to the given value,
211 -- it is replaced with the new value.
212 insert :: Ord a => a -> Set a -> Set a
217 -> case compare x y of
218 LT -> balance y (insert x l) r
219 GT -> balance y l (insert x r)
223 -- | /O(log n)/. Delete an element from a set.
224 delete :: Ord a => a -> Set a -> Set a
229 -> case compare x y of
230 LT -> balance y (delete x l) r
231 GT -> balance y l (delete x r)
234 {--------------------------------------------------------------------
236 --------------------------------------------------------------------}
237 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
238 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
239 isProperSubsetOf s1 s2
240 = (size s1 < size s2) && (isSubsetOf s1 s2)
243 -- | /O(n+m)/. Is this a subset?
244 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
245 isSubsetOf :: Ord a => Set a -> Set a -> Bool
247 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
249 isSubsetOfX Tip t = True
250 isSubsetOfX t Tip = False
251 isSubsetOfX (Bin _ x l r) t
252 = found && isSubsetOfX l lt && isSubsetOfX r gt
254 (lt,found,gt) = splitMember x t
257 {--------------------------------------------------------------------
259 --------------------------------------------------------------------}
260 -- | /O(log n)/. The minimal element of a set.
261 findMin :: Set a -> a
262 findMin (Bin _ x Tip r) = x
263 findMin (Bin _ x l r) = findMin l
264 findMin Tip = error "Set.findMin: empty set has no minimal element"
266 -- | /O(log n)/. The maximal element of a set.
267 findMax :: Set a -> a
268 findMax (Bin _ x l Tip) = x
269 findMax (Bin _ x l r) = findMax r
270 findMax Tip = error "Set.findMax: empty set has no maximal element"
272 -- | /O(log n)/. Delete the minimal element.
273 deleteMin :: Set a -> Set a
274 deleteMin (Bin _ x Tip r) = r
275 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
278 -- | /O(log n)/. Delete the maximal element.
279 deleteMax :: Set a -> Set a
280 deleteMax (Bin _ x l Tip) = l
281 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
285 {--------------------------------------------------------------------
287 --------------------------------------------------------------------}
288 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
289 unions :: Ord a => [Set a] -> Set a
291 = foldlStrict union empty ts
294 -- | /O(n+m)/. The union of two sets, preferring the first set when
295 -- equal elements are encountered.
296 -- The implementation uses the efficient /hedge-union/ algorithm.
297 -- Hedge-union is more efficient on (bigset `union` smallset).
298 union :: Ord a => Set a -> Set a -> Set a
302 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
303 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
305 hedgeUnion cmplo cmphi t1 Tip
307 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
308 = join x (filterGt cmplo l) (filterLt cmphi r)
309 hedgeUnion cmplo cmphi (Bin _ x l r) t2
310 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
311 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
315 {--------------------------------------------------------------------
317 --------------------------------------------------------------------}
318 -- | /O(n+m)/. Difference of two sets.
319 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
320 difference :: Ord a => Set a -> Set a -> Set a
321 difference Tip t2 = Tip
322 difference t1 Tip = t1
323 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
325 hedgeDiff cmplo cmphi Tip t
327 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
328 = join x (filterGt cmplo l) (filterLt cmphi r)
329 hedgeDiff cmplo cmphi t (Bin _ x l r)
330 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
331 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
335 {--------------------------------------------------------------------
337 --------------------------------------------------------------------}
338 -- | /O(n+m)/. The intersection of two sets.
339 -- Intersection is more efficient on (bigset `intersection` smallset).
340 intersection :: Ord a => Set a -> Set a -> Set a
341 intersection Tip t = Tip
342 intersection t Tip = Tip
344 | size t1 >= size t2 = intersect' t1 t2
345 | otherwise = intersect' t2 t1
347 intersect' Tip t = Tip
348 intersect' t Tip = Tip
349 intersect' t (Bin _ x l r)
350 | found = join x tl tr
351 | otherwise = merge tl tr
353 (lt,found,gt) = splitMember x t
358 {--------------------------------------------------------------------
360 --------------------------------------------------------------------}
361 -- | /O(n)/. Filter all elements that satisfy the predicate.
362 filter :: Ord a => (a -> Bool) -> Set a -> Set a
364 filter p (Bin _ x l r)
365 | p x = join x (filter p l) (filter p r)
366 | otherwise = merge (filter p l) (filter p r)
368 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
369 -- the predicate and one with all elements that don't satisfy the predicate.
371 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
372 partition p Tip = (Tip,Tip)
373 partition p (Bin _ x l r)
374 | p x = (join x l1 r1,merge l2 r2)
375 | otherwise = (merge l1 r1,join x l2 r2)
377 (l1,l2) = partition p l
378 (r1,r2) = partition p r
380 {----------------------------------------------------------------------
382 ----------------------------------------------------------------------}
385 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
387 -- It's worth noting that the size of the result may be smaller if,
388 -- for some @(x,y)@, @x \/= y && f x == f y@
390 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
391 map f = fromList . List.map f . toList
395 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
396 -- /The precondition is not checked./
397 -- Semi-formally, we have:
399 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
400 -- > ==> mapMonotonic f s == map f s
401 -- > where ls = toList s
403 mapMonotonic :: (a->b) -> Set a -> Set b
404 mapMonotonic f Tip = Tip
405 mapMonotonic f (Bin sz x l r) =
406 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
409 {--------------------------------------------------------------------
411 --------------------------------------------------------------------}
412 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
413 fold :: (a -> b -> b) -> b -> Set a -> b
417 -- | /O(n)/. Post-order fold.
418 foldr :: (a -> b -> b) -> b -> Set a -> b
420 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
422 {--------------------------------------------------------------------
424 --------------------------------------------------------------------}
425 -- | /O(n)/. The elements of a set.
426 elems :: Set a -> [a]
430 {--------------------------------------------------------------------
432 --------------------------------------------------------------------}
433 -- | /O(n)/. Convert the set to a list of elements.
434 toList :: Set a -> [a]
438 -- | /O(n)/. Convert the set to an ascending list of elements.
439 toAscList :: Set a -> [a]
444 -- | /O(n*log n)/. Create a set from a list of elements.
445 fromList :: Ord a => [a] -> Set a
447 = foldlStrict ins empty xs
451 {--------------------------------------------------------------------
452 Building trees from ascending/descending lists can be done in linear time.
454 Note that if [xs] is ascending that:
455 fromAscList xs == fromList xs
456 --------------------------------------------------------------------}
457 -- | /O(n)/. Build a set from an ascending list in linear time.
458 -- /The precondition (input list is ascending) is not checked./
459 fromAscList :: Eq a => [a] -> Set a
461 = fromDistinctAscList (combineEq xs)
463 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
468 (x:xx) -> combineEq' x xx
470 combineEq' z [] = [z]
472 | z==x = combineEq' z xs
473 | otherwise = z:combineEq' x xs
476 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
477 -- /The precondition (input list is strictly ascending) is not checked./
478 fromDistinctAscList :: [a] -> Set a
479 fromDistinctAscList xs
480 = build const (length xs) xs
482 -- 1) use continutations so that we use heap space instead of stack space.
483 -- 2) special case for n==5 to build bushier trees.
484 build c 0 xs = c Tip xs
485 build c 5 xs = case xs of
487 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
488 build c n xs = seq nr $ build (buildR nr c) nl xs
493 buildR n c l (x:ys) = build (buildB l x c) n ys
494 buildB l x c r zs = c (bin x l r) zs
496 {--------------------------------------------------------------------
497 Eq converts the set to a list. In a lazy setting, this
498 actually seems one of the faster methods to compare two trees
499 and it is certainly the simplest :-)
500 --------------------------------------------------------------------}
501 instance Eq a => Eq (Set a) where
502 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
504 {--------------------------------------------------------------------
506 --------------------------------------------------------------------}
508 instance Ord a => Ord (Set a) where
509 compare s1 s2 = compare (toAscList s1) (toAscList s2)
511 {--------------------------------------------------------------------
513 --------------------------------------------------------------------}
514 instance Show a => Show (Set a) where
515 showsPrec d s = showSet (toAscList s)
517 showSet :: (Show a) => [a] -> ShowS
521 = showChar '{' . shows x . showTail xs
523 showTail [] = showChar '}'
524 showTail (x:xs) = showChar ',' . shows x . showTail xs
527 {--------------------------------------------------------------------
529 --------------------------------------------------------------------}
531 #include "Typeable.h"
532 INSTANCE_TYPEABLE1(Set,setTc,"Set")
534 {--------------------------------------------------------------------
535 Utility functions that return sub-ranges of the original
536 tree. Some functions take a comparison function as argument to
537 allow comparisons against infinite values. A function [cmplo x]
538 should be read as [compare lo x].
540 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
541 and [cmphi x == GT] for the value [x] of the root.
542 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
543 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
545 [split k t] Returns two trees [l] and [r] where all values
546 in [l] are <[k] and all keys in [r] are >[k].
547 [splitMember k t] Just like [split] but also returns whether [k]
548 was found in the tree.
549 --------------------------------------------------------------------}
551 {--------------------------------------------------------------------
552 [trim lo hi t] trims away all subtrees that surely contain no
553 values between the range [lo] to [hi]. The returned tree is either
554 empty or the key of the root is between @lo@ and @hi@.
555 --------------------------------------------------------------------}
556 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
557 trim cmplo cmphi Tip = Tip
558 trim cmplo cmphi t@(Bin sx x l r)
560 LT -> case cmphi x of
562 le -> trim cmplo cmphi l
563 ge -> trim cmplo cmphi r
565 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
566 trimMemberLo lo cmphi Tip = (False,Tip)
567 trimMemberLo lo cmphi t@(Bin sx x l r)
568 = case compare lo x of
569 LT -> case cmphi x of
570 GT -> (member lo t, t)
571 le -> trimMemberLo lo cmphi l
572 GT -> trimMemberLo lo cmphi r
573 EQ -> (True,trim (compare lo) cmphi r)
576 {--------------------------------------------------------------------
577 [filterGt x t] filter all values >[x] from tree [t]
578 [filterLt x t] filter all values <[x] from tree [t]
579 --------------------------------------------------------------------}
580 filterGt :: (a -> Ordering) -> Set a -> Set a
581 filterGt cmp Tip = Tip
582 filterGt cmp (Bin sx x l r)
584 LT -> join x (filterGt cmp l) r
588 filterLt :: (a -> Ordering) -> Set a -> Set a
589 filterLt cmp Tip = Tip
590 filterLt cmp (Bin sx x l r)
593 GT -> join x l (filterLt cmp r)
597 {--------------------------------------------------------------------
599 --------------------------------------------------------------------}
600 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
601 -- where all elements in @set1@ are lower than @x@ and all elements in
602 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
603 split :: Ord a => a -> Set a -> (Set a,Set a)
604 split x Tip = (Tip,Tip)
605 split x (Bin sy y l r)
606 = case compare x y of
607 LT -> let (lt,gt) = split x l in (lt,join y gt r)
608 GT -> let (lt,gt) = split x r in (join y l lt,gt)
611 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
612 -- element was found in the original set.
613 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
614 splitMember x Tip = (Tip,False,Tip)
615 splitMember x (Bin sy y l r)
616 = case compare x y of
617 LT -> let (lt,found,gt) = splitMember x l in (lt,found,join y gt r)
618 GT -> let (lt,found,gt) = splitMember x r in (join y l lt,found,gt)
621 {--------------------------------------------------------------------
622 Utility functions that maintain the balance properties of the tree.
623 All constructors assume that all values in [l] < [x] and all values
624 in [r] > [x], and that [l] and [r] are valid trees.
626 In order of sophistication:
627 [Bin sz x l r] The type constructor.
628 [bin x l r] Maintains the correct size, assumes that both [l]
629 and [r] are balanced with respect to each other.
630 [balance x l r] Restores the balance and size.
631 Assumes that the original tree was balanced and
632 that [l] or [r] has changed by at most one element.
633 [join x l r] Restores balance and size.
635 Furthermore, we can construct a new tree from two trees. Both operations
636 assume that all values in [l] < all values in [r] and that [l] and [r]
638 [glue l r] Glues [l] and [r] together. Assumes that [l] and
639 [r] are already balanced with respect to each other.
640 [merge l r] Merges two trees and restores balance.
642 Note: in contrast to Adam's paper, we use (<=) comparisons instead
643 of (<) comparisons in [join], [merge] and [balance].
644 Quickcheck (on [difference]) showed that this was necessary in order
645 to maintain the invariants. It is quite unsatisfactory that I haven't
646 been able to find out why this is actually the case! Fortunately, it
647 doesn't hurt to be a bit more conservative.
648 --------------------------------------------------------------------}
650 {--------------------------------------------------------------------
652 --------------------------------------------------------------------}
653 join :: a -> Set a -> Set a -> Set a
654 join x Tip r = insertMin x r
655 join x l Tip = insertMax x l
656 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
657 | delta*sizeL <= sizeR = balance z (join x l lz) rz
658 | delta*sizeR <= sizeL = balance y ly (join x ry r)
659 | otherwise = bin x l r
662 -- insertMin and insertMax don't perform potentially expensive comparisons.
663 insertMax,insertMin :: a -> Set a -> Set a
668 -> balance y l (insertMax x r)
674 -> balance y (insertMin x l) r
676 {--------------------------------------------------------------------
677 [merge l r]: merges two trees.
678 --------------------------------------------------------------------}
679 merge :: Set a -> Set a -> Set a
682 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
683 | delta*sizeL <= sizeR = balance y (merge l ly) ry
684 | delta*sizeR <= sizeL = balance x lx (merge rx r)
685 | otherwise = glue l r
687 {--------------------------------------------------------------------
688 [glue l r]: glues two trees together.
689 Assumes that [l] and [r] are already balanced with respect to each other.
690 --------------------------------------------------------------------}
691 glue :: Set a -> Set a -> Set a
695 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
696 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
699 -- | /O(log n)/. Delete and find the minimal element.
701 -- > deleteFindMin set = (findMin set, deleteMin set)
703 deleteFindMin :: Set a -> (a,Set a)
706 Bin _ x Tip r -> (x,r)
707 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
708 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
710 -- | /O(log n)/. Delete and find the maximal element.
712 -- > deleteFindMax set = (findMax set, deleteMax set)
713 deleteFindMax :: Set a -> (a,Set a)
716 Bin _ x l Tip -> (x,l)
717 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
718 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
721 {--------------------------------------------------------------------
722 [balance x l r] balances two trees with value x.
723 The sizes of the trees should balance after decreasing the
724 size of one of them. (a rotation).
726 [delta] is the maximal relative difference between the sizes of
727 two trees, it corresponds with the [w] in Adams' paper,
728 or equivalently, [1/delta] corresponds with the $\alpha$
729 in Nievergelt's paper. Adams shows that [delta] should
730 be larger than 3.745 in order to garantee that the
731 rotations can always restore balance.
733 [ratio] is the ratio between an outer and inner sibling of the
734 heavier subtree in an unbalanced setting. It determines
735 whether a double or single rotation should be performed
736 to restore balance. It is correspondes with the inverse
737 of $\alpha$ in Adam's article.
740 - [delta] should be larger than 4.646 with a [ratio] of 2.
741 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
743 - A lower [delta] leads to a more 'perfectly' balanced tree.
744 - A higher [delta] performs less rebalancing.
746 - Balancing is automatic for random data and a balancing
747 scheme is only necessary to avoid pathological worst cases.
748 Almost any choice will do in practice
750 - Allthough it seems that a rather large [delta] may perform better
751 than smaller one, measurements have shown that the smallest [delta]
752 of 4 is actually the fastest on a wide range of operations. It
753 especially improves performance on worst-case scenarios like
754 a sequence of ordered insertions.
756 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
757 to decide whether a single or double rotation is needed. Allthough
758 he actually proves that this ratio is needed to maintain the
759 invariants, his implementation uses a (invalid) ratio of 1.
760 He is aware of the problem though since he has put a comment in his
761 original source code that he doesn't care about generating a
762 slightly inbalanced tree since it doesn't seem to matter in practice.
763 However (since we use quickcheck :-) we will stick to strictly balanced
765 --------------------------------------------------------------------}
770 balance :: a -> Set a -> Set a -> Set a
772 | sizeL + sizeR <= 1 = Bin sizeX x l r
773 | sizeR >= delta*sizeL = rotateL x l r
774 | sizeL >= delta*sizeR = rotateR x l r
775 | otherwise = Bin sizeX x l r
779 sizeX = sizeL + sizeR + 1
782 rotateL x l r@(Bin _ _ ly ry)
783 | size ly < ratio*size ry = singleL x l r
784 | otherwise = doubleL x l r
786 rotateR x l@(Bin _ _ ly ry) r
787 | size ry < ratio*size ly = singleR x l r
788 | otherwise = doubleR x l r
791 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
792 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
794 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
795 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
798 {--------------------------------------------------------------------
799 The bin constructor maintains the size of the tree
800 --------------------------------------------------------------------}
801 bin :: a -> Set a -> Set a -> Set a
803 = Bin (size l + size r + 1) x l r
806 {--------------------------------------------------------------------
808 --------------------------------------------------------------------}
812 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
815 {--------------------------------------------------------------------
817 --------------------------------------------------------------------}
818 -- | /O(n)/. Show the tree that implements the set. The tree is shown
819 -- in a compressed, hanging format.
820 showTree :: Show a => Set a -> String
822 = showTreeWith True False s
825 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
826 the tree that implements the set. If @hang@ is
827 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
828 @wide@ is 'True', an extra wide version is shown.
830 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
837 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
848 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
860 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
861 showTreeWith hang wide t
862 | hang = (showsTreeHang wide [] t) ""
863 | otherwise = (showsTree wide [] [] t) ""
865 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
866 showsTree wide lbars rbars t
868 Tip -> showsBars lbars . showString "|\n"
870 -> showsBars lbars . shows x . showString "\n"
872 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
873 showWide wide rbars .
874 showsBars lbars . shows x . showString "\n" .
875 showWide wide lbars .
876 showsTree wide (withEmpty lbars) (withBar lbars) l
878 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
879 showsTreeHang wide bars t
881 Tip -> showsBars bars . showString "|\n"
883 -> showsBars bars . shows x . showString "\n"
885 -> showsBars bars . shows x . showString "\n" .
887 showsTreeHang wide (withBar bars) l .
889 showsTreeHang wide (withEmpty bars) r
893 | wide = showString (concat (reverse bars)) . showString "|\n"
896 showsBars :: [String] -> ShowS
900 _ -> showString (concat (reverse (tail bars))) . showString node
903 withBar bars = "| ":bars
904 withEmpty bars = " ":bars
906 {--------------------------------------------------------------------
908 --------------------------------------------------------------------}
909 -- | /O(n)/. Test if the internal set structure is valid.
910 valid :: Ord a => Set a -> Bool
912 = balanced t && ordered t && validsize t
915 = bounded (const True) (const True) t
920 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
922 balanced :: Set a -> Bool
926 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
927 balanced l && balanced r
931 = (realsize t == Just (size t))
936 Bin sz x l r -> case (realsize l,realsize r) of
937 (Just n,Just m) | n+m+1 == sz -> Just sz
941 {--------------------------------------------------------------------
943 --------------------------------------------------------------------}
944 testTree :: [Int] -> Set Int
945 testTree xs = fromList xs
946 test1 = testTree [1..20]
947 test2 = testTree [30,29..10]
948 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
950 {--------------------------------------------------------------------
952 --------------------------------------------------------------------}
957 { configMaxTest = 500
958 , configMaxFail = 5000
959 , configSize = \n -> (div n 2 + 3)
960 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
964 {--------------------------------------------------------------------
965 Arbitrary, reasonably balanced trees
966 --------------------------------------------------------------------}
967 instance (Enum a) => Arbitrary (Set a) where
968 arbitrary = sized (arbtree 0 maxkey)
971 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
973 | n <= 0 = return Tip
974 | lo >= hi = return Tip
975 | otherwise = do{ i <- choose (lo,hi)
977 ; let (ml,mr) | m==(1::Int)= (1,2)
981 ; l <- arbtree lo (i-1) (n `div` ml)
982 ; r <- arbtree (i+1) hi (n `div` mr)
983 ; return (bin (toEnum i) l r)
987 {--------------------------------------------------------------------
989 --------------------------------------------------------------------}
990 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
992 = forAll arbitrary $ \t ->
993 -- classify (balanced t) "balanced" $
994 classify (size t == 0) "empty" $
995 classify (size t > 0 && size t <= 10) "small" $
996 classify (size t > 10 && size t <= 64) "medium" $
997 classify (size t > 64) "large" $
1000 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1004 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1010 = forValidUnitTree $ \t -> valid t
1012 {--------------------------------------------------------------------
1013 Single, Insert, Delete
1014 --------------------------------------------------------------------}
1015 prop_Single :: Int -> Bool
1017 = (insert x empty == singleton x)
1019 prop_InsertValid :: Int -> Property
1021 = forValidUnitTree $ \t -> valid (insert k t)
1023 prop_InsertDelete :: Int -> Set Int -> Property
1024 prop_InsertDelete k t
1025 = not (member k t) ==> delete k (insert k t) == t
1027 prop_DeleteValid :: Int -> Property
1029 = forValidUnitTree $ \t ->
1030 valid (delete k (insert k t))
1032 {--------------------------------------------------------------------
1034 --------------------------------------------------------------------}
1035 prop_Join :: Int -> Property
1037 = forValidUnitTree $ \t ->
1038 let (l,r) = split x t
1039 in valid (join x l r)
1041 prop_Merge :: Int -> Property
1043 = forValidUnitTree $ \t ->
1044 let (l,r) = split x t
1045 in valid (merge l r)
1048 {--------------------------------------------------------------------
1050 --------------------------------------------------------------------}
1051 prop_UnionValid :: Property
1053 = forValidUnitTree $ \t1 ->
1054 forValidUnitTree $ \t2 ->
1057 prop_UnionInsert :: Int -> Set Int -> Bool
1058 prop_UnionInsert x t
1059 = union t (singleton x) == insert x t
1061 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1062 prop_UnionAssoc t1 t2 t3
1063 = union t1 (union t2 t3) == union (union t1 t2) t3
1065 prop_UnionComm :: Set Int -> Set Int -> Bool
1066 prop_UnionComm t1 t2
1067 = (union t1 t2 == union t2 t1)
1071 = forValidUnitTree $ \t1 ->
1072 forValidUnitTree $ \t2 ->
1073 valid (difference t1 t2)
1075 prop_Diff :: [Int] -> [Int] -> Bool
1077 = toAscList (difference (fromList xs) (fromList ys))
1078 == List.sort ((List.\\) (nub xs) (nub ys))
1081 = forValidUnitTree $ \t1 ->
1082 forValidUnitTree $ \t2 ->
1083 valid (intersection t1 t2)
1085 prop_Int :: [Int] -> [Int] -> Bool
1087 = toAscList (intersection (fromList xs) (fromList ys))
1088 == List.sort (nub ((List.intersect) (xs) (ys)))
1090 {--------------------------------------------------------------------
1092 --------------------------------------------------------------------}
1094 = forAll (choose (5,100)) $ \n ->
1095 let xs = [0..n::Int]
1096 in fromAscList xs == fromList xs
1098 prop_List :: [Int] -> Bool
1100 = (sort (nub xs) == toList (fromList xs))
1103 {--------------------------------------------------------------------
1104 Old Data.Set compatibility interface
1105 --------------------------------------------------------------------}
1107 {-# DEPRECATED emptySet "Use empty instead" #-}
1108 -- | Obsolete equivalent of 'empty'.
1112 {-# DEPRECATED mkSet "Use fromList instead" #-}
1113 -- | Obsolete equivalent of 'fromList'.
1114 mkSet :: Ord a => [a] -> Set a
1117 {-# DEPRECATED setToList "Use elems instead." #-}
1118 -- | Obsolete equivalent of 'elems'.
1119 setToList :: Set a -> [a]
1122 {-# DEPRECATED unitSet "Use singleton instead." #-}
1123 -- | Obsolete equivalent of 'singleton'.
1124 unitSet :: a -> Set a
1127 {-# DEPRECATED elementOf "Use member instead." #-}
1128 -- | Obsolete equivalent of 'member'.
1129 elementOf :: Ord a => a -> Set a -> Bool
1132 {-# DEPRECATED isEmptySet "Use null instead." #-}
1133 -- | Obsolete equivalent of 'null'.
1134 isEmptySet :: Set a -> Bool
1137 {-# DEPRECATED cardinality "Use size instead." #-}
1138 -- | Obsolete equivalent of 'size'.
1139 cardinality :: Set a -> Int
1142 {-# DEPRECATED unionManySets "Use unions instead." #-}
1143 -- | Obsolete equivalent of 'unions'.
1144 unionManySets :: Ord a => [Set a] -> Set a
1145 unionManySets = unions
1147 {-# DEPRECATED minusSet "Use difference instead." #-}
1148 -- | Obsolete equivalent of 'difference'.
1149 minusSet :: Ord a => Set a -> Set a -> Set a
1150 minusSet = difference
1152 {-# DEPRECATED mapSet "Use map instead." #-}
1153 -- | Obsolete equivalent of 'map'.
1154 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1157 {-# DEPRECATED intersect "Use intersection instead." #-}
1158 -- | Obsolete equivalent of 'intersection'.
1159 intersect :: Ord a => Set a -> Set a -> Set a
1160 intersect = intersection
1162 {-# DEPRECATED addToSet "Use 'flip insert' instead." #-}
1163 -- | Obsolete equivalent of @'flip' 'insert'@.
1164 addToSet :: Ord a => Set a -> a -> Set a
1165 addToSet = flip insert
1167 {-# DEPRECATED delFromSet "Use `flip delete' instead." #-}
1168 -- | Obsolete equivalent of @'flip' 'delete'@.
1169 delFromSet :: Ord a => Set a -> a -> Set a
1170 delFromSet = flip delete