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 preferred to the second, for example in
30 -- 'union' or 'insert'. Of course, left-biasing can only be observed
31 -- when equality is an equivalence relation instead of structural
33 -----------------------------------------------------------------------------
37 Set -- instance Eq,Ord,Show,Read,Data,Typeable
99 -- * Old interface, DEPRECATED
100 ,emptySet, -- :: Set a
101 mkSet, -- :: Ord a => [a] -> Set a
102 setToList, -- :: Set a -> [a]
103 unitSet, -- :: a -> Set a
104 elementOf, -- :: Ord a => a -> Set a -> Bool
105 isEmptySet, -- :: Set a -> Bool
106 cardinality, -- :: Set a -> Int
107 unionManySets, -- :: Ord a => [Set a] -> Set a
108 minusSet, -- :: Ord a => Set a -> Set a -> Set a
109 mapSet, -- :: Ord a => (b -> a) -> Set b -> Set a
110 intersect, -- :: Ord a => Set a -> Set a -> Set a
111 addToSet, -- :: Ord a => Set a -> a -> Set a
112 delFromSet, -- :: Ord a => Set a -> a -> Set a
115 import Prelude hiding (filter,foldr,null,map)
116 import qualified Data.List as List
117 import Data.Monoid (Monoid(..))
119 import Data.Foldable (Foldable(foldMap))
124 import List (nub,sort)
125 import qualified List
128 #if __GLASGOW_HASKELL__
130 import Data.Generics.Basics
131 import Data.Generics.Instances
134 {--------------------------------------------------------------------
136 --------------------------------------------------------------------}
139 -- | /O(n+m)/. See 'difference'.
140 (\\) :: Ord a => Set a -> Set a -> Set a
141 m1 \\ m2 = difference m1 m2
143 {--------------------------------------------------------------------
144 Sets are size balanced trees
145 --------------------------------------------------------------------}
146 -- | A set of values @a@.
148 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
152 instance Ord a => Monoid (Set a) where
157 instance Foldable Set where
158 foldMap f Tip = mempty
159 foldMap f (Bin _s k l r) = foldMap f l `mappend` f k `mappend` foldMap f r
161 #if __GLASGOW_HASKELL__
163 {--------------------------------------------------------------------
165 --------------------------------------------------------------------}
167 -- This instance preserves data abstraction at the cost of inefficiency.
168 -- We omit reflection services for the sake of data abstraction.
170 instance (Data a, Ord a) => Data (Set a) where
171 gfoldl f z set = z fromList `f` (toList set)
172 toConstr _ = error "toConstr"
173 gunfold _ _ = error "gunfold"
174 dataTypeOf _ = mkNorepType "Data.Set.Set"
175 dataCast1 f = gcast1 f
179 {--------------------------------------------------------------------
181 --------------------------------------------------------------------}
182 -- | /O(1)/. Is this the empty set?
183 null :: Set a -> Bool
187 Bin sz x l r -> False
189 -- | /O(1)/. The number of elements in the set.
196 -- | /O(log n)/. Is the element in the set?
197 member :: Ord a => a -> Set a -> Bool
202 -> case compare x y of
207 -- | /O(log n)/. Is the element not in the set?
208 notMember :: Ord a => a -> Set a -> Bool
209 notMember x t = not $ Data.Set.member x t
212 {--------------------------------------------------------------------
214 --------------------------------------------------------------------}
215 -- | /O(1)/. The empty set.
220 -- | /O(1)/. Create a singleton set.
221 singleton :: a -> Set a
225 {--------------------------------------------------------------------
227 --------------------------------------------------------------------}
228 -- | /O(log n)/. Insert an element in a set.
229 -- If the set already contains an element equal to the given value,
230 -- it is replaced with the new value.
231 insert :: Ord a => a -> Set a -> Set a
236 -> case compare x y of
237 LT -> balance y (insert x l) r
238 GT -> balance y l (insert x r)
242 -- | /O(log n)/. Delete an element from a set.
243 delete :: Ord a => a -> Set a -> Set a
248 -> case compare x y of
249 LT -> balance y (delete x l) r
250 GT -> balance y l (delete x r)
253 {--------------------------------------------------------------------
255 --------------------------------------------------------------------}
256 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
257 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
258 isProperSubsetOf s1 s2
259 = (size s1 < size s2) && (isSubsetOf s1 s2)
262 -- | /O(n+m)/. Is this a subset?
263 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
264 isSubsetOf :: Ord a => Set a -> Set a -> Bool
266 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
268 isSubsetOfX Tip t = True
269 isSubsetOfX t Tip = False
270 isSubsetOfX (Bin _ x l r) t
271 = found && isSubsetOfX l lt && isSubsetOfX r gt
273 (lt,found,gt) = splitMember x t
276 {--------------------------------------------------------------------
278 --------------------------------------------------------------------}
279 -- | /O(log n)/. The minimal element of a set.
280 findMin :: Set a -> a
281 findMin (Bin _ x Tip r) = x
282 findMin (Bin _ x l r) = findMin l
283 findMin Tip = error "Set.findMin: empty set has no minimal element"
285 -- | /O(log n)/. The maximal element of a set.
286 findMax :: Set a -> a
287 findMax (Bin _ x l Tip) = x
288 findMax (Bin _ x l r) = findMax r
289 findMax Tip = error "Set.findMax: empty set has no maximal element"
291 -- | /O(log n)/. Delete the minimal element.
292 deleteMin :: Set a -> Set a
293 deleteMin (Bin _ x Tip r) = r
294 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
297 -- | /O(log n)/. Delete the maximal element.
298 deleteMax :: Set a -> Set a
299 deleteMax (Bin _ x l Tip) = l
300 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
304 {--------------------------------------------------------------------
306 --------------------------------------------------------------------}
307 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
308 unions :: Ord a => [Set a] -> Set a
310 = foldlStrict union empty ts
313 -- | /O(n+m)/. The union of two sets, preferring the first set when
314 -- equal elements are encountered.
315 -- The implementation uses the efficient /hedge-union/ algorithm.
316 -- Hedge-union is more efficient on (bigset `union` smallset).
317 union :: Ord a => Set a -> Set a -> Set a
320 union t1 t2 = hedgeUnion (const LT) (const GT) t1 t2
322 hedgeUnion cmplo cmphi t1 Tip
324 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
325 = join x (filterGt cmplo l) (filterLt cmphi r)
326 hedgeUnion cmplo cmphi (Bin _ x l r) t2
327 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
328 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
332 {--------------------------------------------------------------------
334 --------------------------------------------------------------------}
335 -- | /O(n+m)/. Difference of two sets.
336 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
337 difference :: Ord a => Set a -> Set a -> Set a
338 difference Tip t2 = Tip
339 difference t1 Tip = t1
340 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
342 hedgeDiff cmplo cmphi Tip t
344 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
345 = join x (filterGt cmplo l) (filterLt cmphi r)
346 hedgeDiff cmplo cmphi t (Bin _ x l r)
347 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
348 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
352 {--------------------------------------------------------------------
354 --------------------------------------------------------------------}
355 -- | /O(n+m)/. The intersection of two sets.
356 -- Elements of the result come from the first set.
357 intersection :: Ord a => Set a -> Set a -> Set a
358 intersection Tip t = Tip
359 intersection t Tip = Tip
360 intersection t1@(Bin s1 x1 l1 r1) t2@(Bin s2 x2 l2 r2) =
362 let (lt,found,gt) = splitLookup x2 t1
363 tl = intersection lt l2
364 tr = intersection gt r2
366 Just x -> join x tl tr
367 Nothing -> merge tl tr
368 else let (lt,found,gt) = splitMember x1 t2
369 tl = intersection l1 lt
370 tr = intersection r1 gt
371 in if found then join x1 tl tr
374 {--------------------------------------------------------------------
376 --------------------------------------------------------------------}
377 -- | /O(n)/. Filter all elements that satisfy the predicate.
378 filter :: Ord a => (a -> Bool) -> Set a -> Set a
380 filter p (Bin _ x l r)
381 | p x = join x (filter p l) (filter p r)
382 | otherwise = merge (filter p l) (filter p r)
384 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
385 -- the predicate and one with all elements that don't satisfy the predicate.
387 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
388 partition p Tip = (Tip,Tip)
389 partition p (Bin _ x l r)
390 | p x = (join x l1 r1,merge l2 r2)
391 | otherwise = (merge l1 r1,join x l2 r2)
393 (l1,l2) = partition p l
394 (r1,r2) = partition p r
396 {----------------------------------------------------------------------
398 ----------------------------------------------------------------------}
401 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
403 -- It's worth noting that the size of the result may be smaller if,
404 -- for some @(x,y)@, @x \/= y && f x == f y@
406 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
407 map f = fromList . List.map f . toList
411 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
412 -- /The precondition is not checked./
413 -- Semi-formally, we have:
415 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
416 -- > ==> mapMonotonic f s == map f s
417 -- > where ls = toList s
419 mapMonotonic :: (a->b) -> Set a -> Set b
420 mapMonotonic f Tip = Tip
421 mapMonotonic f (Bin sz x l r) =
422 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
425 {--------------------------------------------------------------------
427 --------------------------------------------------------------------}
428 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
429 fold :: (a -> b -> b) -> b -> Set a -> b
433 -- | /O(n)/. Post-order fold.
434 foldr :: (a -> b -> b) -> b -> Set a -> b
436 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
438 {--------------------------------------------------------------------
440 --------------------------------------------------------------------}
441 -- | /O(n)/. The elements of a set.
442 elems :: Set a -> [a]
446 {--------------------------------------------------------------------
448 --------------------------------------------------------------------}
449 -- | /O(n)/. Convert the set to a list of elements.
450 toList :: Set a -> [a]
454 -- | /O(n)/. Convert the set to an ascending list of elements.
455 toAscList :: Set a -> [a]
460 -- | /O(n*log n)/. Create a set from a list of elements.
461 fromList :: Ord a => [a] -> Set a
463 = foldlStrict ins empty xs
467 {--------------------------------------------------------------------
468 Building trees from ascending/descending lists can be done in linear time.
470 Note that if [xs] is ascending that:
471 fromAscList xs == fromList xs
472 --------------------------------------------------------------------}
473 -- | /O(n)/. Build a set from an ascending list in linear time.
474 -- /The precondition (input list is ascending) is not checked./
475 fromAscList :: Eq a => [a] -> Set a
477 = fromDistinctAscList (combineEq xs)
479 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
484 (x:xx) -> combineEq' x xx
486 combineEq' z [] = [z]
488 | z==x = combineEq' z xs
489 | otherwise = z:combineEq' x xs
492 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
493 -- /The precondition (input list is strictly ascending) is not checked./
494 fromDistinctAscList :: [a] -> Set a
495 fromDistinctAscList xs
496 = build const (length xs) xs
498 -- 1) use continutations so that we use heap space instead of stack space.
499 -- 2) special case for n==5 to build bushier trees.
500 build c 0 xs = c Tip xs
501 build c 5 xs = case xs of
503 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
504 build c n xs = seq nr $ build (buildR nr c) nl xs
509 buildR n c l (x:ys) = build (buildB l x c) n ys
510 buildB l x c r zs = c (bin x l r) zs
512 {--------------------------------------------------------------------
513 Eq converts the set to a list. In a lazy setting, this
514 actually seems one of the faster methods to compare two trees
515 and it is certainly the simplest :-)
516 --------------------------------------------------------------------}
517 instance Eq a => Eq (Set a) where
518 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
520 {--------------------------------------------------------------------
522 --------------------------------------------------------------------}
524 instance Ord a => Ord (Set a) where
525 compare s1 s2 = compare (toAscList s1) (toAscList s2)
527 {--------------------------------------------------------------------
529 --------------------------------------------------------------------}
530 instance Show a => Show (Set a) where
531 showsPrec p xs = showParen (p > 10) $
532 showString "fromList " . shows (toList xs)
534 showSet :: (Show a) => [a] -> ShowS
538 = showChar '{' . shows x . showTail xs
540 showTail [] = showChar '}'
541 showTail (x:xs) = showChar ',' . shows x . showTail xs
543 {--------------------------------------------------------------------
545 --------------------------------------------------------------------}
546 instance (Read a, Ord a) => Read (Set a) where
547 #ifdef __GLASGOW_HASKELL__
548 readPrec = parens $ prec 10 $ do
549 Ident "fromList" <- lexP
553 readListPrec = readListPrecDefault
555 readsPrec p = readParen (p > 10) $ \ r -> do
556 ("fromList",s) <- lex r
558 return (fromList xs,t)
561 {--------------------------------------------------------------------
563 --------------------------------------------------------------------}
565 #include "Typeable.h"
566 INSTANCE_TYPEABLE1(Set,setTc,"Set")
568 {--------------------------------------------------------------------
569 Utility functions that return sub-ranges of the original
570 tree. Some functions take a comparison function as argument to
571 allow comparisons against infinite values. A function [cmplo x]
572 should be read as [compare lo x].
574 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
575 and [cmphi x == GT] for the value [x] of the root.
576 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
577 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
579 [split k t] Returns two trees [l] and [r] where all values
580 in [l] are <[k] and all keys in [r] are >[k].
581 [splitMember k t] Just like [split] but also returns whether [k]
582 was found in the tree.
583 --------------------------------------------------------------------}
585 {--------------------------------------------------------------------
586 [trim lo hi t] trims away all subtrees that surely contain no
587 values between the range [lo] to [hi]. The returned tree is either
588 empty or the key of the root is between @lo@ and @hi@.
589 --------------------------------------------------------------------}
590 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
591 trim cmplo cmphi Tip = Tip
592 trim cmplo cmphi t@(Bin sx x l r)
594 LT -> case cmphi x of
596 le -> trim cmplo cmphi l
597 ge -> trim cmplo cmphi r
599 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
600 trimMemberLo lo cmphi Tip = (False,Tip)
601 trimMemberLo lo cmphi t@(Bin sx x l r)
602 = case compare lo x of
603 LT -> case cmphi x of
604 GT -> (member lo t, t)
605 le -> trimMemberLo lo cmphi l
606 GT -> trimMemberLo lo cmphi r
607 EQ -> (True,trim (compare lo) cmphi r)
610 {--------------------------------------------------------------------
611 [filterGt x t] filter all values >[x] from tree [t]
612 [filterLt x t] filter all values <[x] from tree [t]
613 --------------------------------------------------------------------}
614 filterGt :: (a -> Ordering) -> Set a -> Set a
615 filterGt cmp Tip = Tip
616 filterGt cmp (Bin sx x l r)
618 LT -> join x (filterGt cmp l) r
622 filterLt :: (a -> Ordering) -> Set a -> Set a
623 filterLt cmp Tip = Tip
624 filterLt cmp (Bin sx x l r)
627 GT -> join x l (filterLt cmp r)
631 {--------------------------------------------------------------------
633 --------------------------------------------------------------------}
634 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
635 -- where all elements in @set1@ are lower than @x@ and all elements in
636 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
637 split :: Ord a => a -> Set a -> (Set a,Set a)
638 split x Tip = (Tip,Tip)
639 split x (Bin sy y l r)
640 = case compare x y of
641 LT -> let (lt,gt) = split x l in (lt,join y gt r)
642 GT -> let (lt,gt) = split x r in (join y l lt,gt)
645 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
646 -- element was found in the original set.
647 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
648 splitMember x t = let (l,m,r) = splitLookup x t in
649 (l,maybe False (const True) m,r)
651 -- | /O(log n)/. Performs a 'split' but also returns the pivot
652 -- element that was found in the original set.
653 splitLookup :: Ord a => a -> Set a -> (Set a,Maybe a,Set a)
654 splitLookup x Tip = (Tip,Nothing,Tip)
655 splitLookup x (Bin sy y l r)
656 = case compare x y of
657 LT -> let (lt,found,gt) = splitLookup x l in (lt,found,join y gt r)
658 GT -> let (lt,found,gt) = splitLookup x r in (join y l lt,found,gt)
661 {--------------------------------------------------------------------
662 Utility functions that maintain the balance properties of the tree.
663 All constructors assume that all values in [l] < [x] and all values
664 in [r] > [x], and that [l] and [r] are valid trees.
666 In order of sophistication:
667 [Bin sz x l r] The type constructor.
668 [bin x l r] Maintains the correct size, assumes that both [l]
669 and [r] are balanced with respect to each other.
670 [balance x l r] Restores the balance and size.
671 Assumes that the original tree was balanced and
672 that [l] or [r] has changed by at most one element.
673 [join x l r] Restores balance and size.
675 Furthermore, we can construct a new tree from two trees. Both operations
676 assume that all values in [l] < all values in [r] and that [l] and [r]
678 [glue l r] Glues [l] and [r] together. Assumes that [l] and
679 [r] are already balanced with respect to each other.
680 [merge l r] Merges two trees and restores balance.
682 Note: in contrast to Adam's paper, we use (<=) comparisons instead
683 of (<) comparisons in [join], [merge] and [balance].
684 Quickcheck (on [difference]) showed that this was necessary in order
685 to maintain the invariants. It is quite unsatisfactory that I haven't
686 been able to find out why this is actually the case! Fortunately, it
687 doesn't hurt to be a bit more conservative.
688 --------------------------------------------------------------------}
690 {--------------------------------------------------------------------
692 --------------------------------------------------------------------}
693 join :: a -> Set a -> Set a -> Set a
694 join x Tip r = insertMin x r
695 join x l Tip = insertMax x l
696 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
697 | delta*sizeL <= sizeR = balance z (join x l lz) rz
698 | delta*sizeR <= sizeL = balance y ly (join x ry r)
699 | otherwise = bin x l r
702 -- insertMin and insertMax don't perform potentially expensive comparisons.
703 insertMax,insertMin :: a -> Set a -> Set a
708 -> balance y l (insertMax x r)
714 -> balance y (insertMin x l) r
716 {--------------------------------------------------------------------
717 [merge l r]: merges two trees.
718 --------------------------------------------------------------------}
719 merge :: Set a -> Set a -> Set a
722 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
723 | delta*sizeL <= sizeR = balance y (merge l ly) ry
724 | delta*sizeR <= sizeL = balance x lx (merge rx r)
725 | otherwise = glue l r
727 {--------------------------------------------------------------------
728 [glue l r]: glues two trees together.
729 Assumes that [l] and [r] are already balanced with respect to each other.
730 --------------------------------------------------------------------}
731 glue :: Set a -> Set a -> Set a
735 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
736 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
739 -- | /O(log n)/. Delete and find the minimal element.
741 -- > deleteFindMin set = (findMin set, deleteMin set)
743 deleteFindMin :: Set a -> (a,Set a)
746 Bin _ x Tip r -> (x,r)
747 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
748 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
750 -- | /O(log n)/. Delete and find the maximal element.
752 -- > deleteFindMax set = (findMax set, deleteMax set)
753 deleteFindMax :: Set a -> (a,Set a)
756 Bin _ x l Tip -> (x,l)
757 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
758 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
761 {--------------------------------------------------------------------
762 [balance x l r] balances two trees with value x.
763 The sizes of the trees should balance after decreasing the
764 size of one of them. (a rotation).
766 [delta] is the maximal relative difference between the sizes of
767 two trees, it corresponds with the [w] in Adams' paper,
768 or equivalently, [1/delta] corresponds with the $\alpha$
769 in Nievergelt's paper. Adams shows that [delta] should
770 be larger than 3.745 in order to garantee that the
771 rotations can always restore balance.
773 [ratio] is the ratio between an outer and inner sibling of the
774 heavier subtree in an unbalanced setting. It determines
775 whether a double or single rotation should be performed
776 to restore balance. It is correspondes with the inverse
777 of $\alpha$ in Adam's article.
780 - [delta] should be larger than 4.646 with a [ratio] of 2.
781 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
783 - A lower [delta] leads to a more 'perfectly' balanced tree.
784 - A higher [delta] performs less rebalancing.
786 - Balancing is automatic for random data and a balancing
787 scheme is only necessary to avoid pathological worst cases.
788 Almost any choice will do in practice
790 - Allthough it seems that a rather large [delta] may perform better
791 than smaller one, measurements have shown that the smallest [delta]
792 of 4 is actually the fastest on a wide range of operations. It
793 especially improves performance on worst-case scenarios like
794 a sequence of ordered insertions.
796 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
797 to decide whether a single or double rotation is needed. Allthough
798 he actually proves that this ratio is needed to maintain the
799 invariants, his implementation uses a (invalid) ratio of 1.
800 He is aware of the problem though since he has put a comment in his
801 original source code that he doesn't care about generating a
802 slightly inbalanced tree since it doesn't seem to matter in practice.
803 However (since we use quickcheck :-) we will stick to strictly balanced
805 --------------------------------------------------------------------}
810 balance :: a -> Set a -> Set a -> Set a
812 | sizeL + sizeR <= 1 = Bin sizeX x l r
813 | sizeR >= delta*sizeL = rotateL x l r
814 | sizeL >= delta*sizeR = rotateR x l r
815 | otherwise = Bin sizeX x l r
819 sizeX = sizeL + sizeR + 1
822 rotateL x l r@(Bin _ _ ly ry)
823 | size ly < ratio*size ry = singleL x l r
824 | otherwise = doubleL x l r
826 rotateR x l@(Bin _ _ ly ry) r
827 | size ry < ratio*size ly = singleR x l r
828 | otherwise = doubleR x l r
831 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
832 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
834 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
835 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
838 {--------------------------------------------------------------------
839 The bin constructor maintains the size of the tree
840 --------------------------------------------------------------------}
841 bin :: a -> Set a -> Set a -> Set a
843 = Bin (size l + size r + 1) x l r
846 {--------------------------------------------------------------------
848 --------------------------------------------------------------------}
852 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
855 {--------------------------------------------------------------------
857 --------------------------------------------------------------------}
858 -- | /O(n)/. Show the tree that implements the set. The tree is shown
859 -- in a compressed, hanging format.
860 showTree :: Show a => Set a -> String
862 = showTreeWith True False s
865 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
866 the tree that implements the set. If @hang@ is
867 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
868 @wide@ is 'True', an extra wide version is shown.
870 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
877 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
888 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
900 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
901 showTreeWith hang wide t
902 | hang = (showsTreeHang wide [] t) ""
903 | otherwise = (showsTree wide [] [] t) ""
905 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
906 showsTree wide lbars rbars t
908 Tip -> showsBars lbars . showString "|\n"
910 -> showsBars lbars . shows x . showString "\n"
912 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
913 showWide wide rbars .
914 showsBars lbars . shows x . showString "\n" .
915 showWide wide lbars .
916 showsTree wide (withEmpty lbars) (withBar lbars) l
918 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
919 showsTreeHang wide bars t
921 Tip -> showsBars bars . showString "|\n"
923 -> showsBars bars . shows x . showString "\n"
925 -> showsBars bars . shows x . showString "\n" .
927 showsTreeHang wide (withBar bars) l .
929 showsTreeHang wide (withEmpty bars) r
933 | wide = showString (concat (reverse bars)) . showString "|\n"
936 showsBars :: [String] -> ShowS
940 _ -> showString (concat (reverse (tail bars))) . showString node
943 withBar bars = "| ":bars
944 withEmpty bars = " ":bars
946 {--------------------------------------------------------------------
948 --------------------------------------------------------------------}
949 -- | /O(n)/. Test if the internal set structure is valid.
950 valid :: Ord a => Set a -> Bool
952 = balanced t && ordered t && validsize t
955 = bounded (const True) (const True) t
960 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
962 balanced :: Set a -> Bool
966 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
967 balanced l && balanced r
971 = (realsize t == Just (size t))
976 Bin sz x l r -> case (realsize l,realsize r) of
977 (Just n,Just m) | n+m+1 == sz -> Just sz
981 {--------------------------------------------------------------------
983 --------------------------------------------------------------------}
984 testTree :: [Int] -> Set Int
985 testTree xs = fromList xs
986 test1 = testTree [1..20]
987 test2 = testTree [30,29..10]
988 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
990 {--------------------------------------------------------------------
992 --------------------------------------------------------------------}
997 { configMaxTest = 500
998 , configMaxFail = 5000
999 , configSize = \n -> (div n 2 + 3)
1000 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1004 {--------------------------------------------------------------------
1005 Arbitrary, reasonably balanced trees
1006 --------------------------------------------------------------------}
1007 instance (Enum a) => Arbitrary (Set a) where
1008 arbitrary = sized (arbtree 0 maxkey)
1009 where maxkey = 10000
1011 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
1013 | n <= 0 = return Tip
1014 | lo >= hi = return Tip
1015 | otherwise = do{ i <- choose (lo,hi)
1016 ; m <- choose (1,30)
1017 ; let (ml,mr) | m==(1::Int)= (1,2)
1021 ; l <- arbtree lo (i-1) (n `div` ml)
1022 ; r <- arbtree (i+1) hi (n `div` mr)
1023 ; return (bin (toEnum i) l r)
1027 {--------------------------------------------------------------------
1029 --------------------------------------------------------------------}
1030 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1032 = forAll arbitrary $ \t ->
1033 -- classify (balanced t) "balanced" $
1034 classify (size t == 0) "empty" $
1035 classify (size t > 0 && size t <= 10) "small" $
1036 classify (size t > 10 && size t <= 64) "medium" $
1037 classify (size t > 64) "large" $
1040 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1044 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1050 = forValidUnitTree $ \t -> valid t
1052 {--------------------------------------------------------------------
1053 Single, Insert, Delete
1054 --------------------------------------------------------------------}
1055 prop_Single :: Int -> Bool
1057 = (insert x empty == singleton x)
1059 prop_InsertValid :: Int -> Property
1061 = forValidUnitTree $ \t -> valid (insert k t)
1063 prop_InsertDelete :: Int -> Set Int -> Property
1064 prop_InsertDelete k t
1065 = not (member k t) ==> delete k (insert k t) == t
1067 prop_DeleteValid :: Int -> Property
1069 = forValidUnitTree $ \t ->
1070 valid (delete k (insert k t))
1072 {--------------------------------------------------------------------
1074 --------------------------------------------------------------------}
1075 prop_Join :: Int -> Property
1077 = forValidUnitTree $ \t ->
1078 let (l,r) = split x t
1079 in valid (join x l r)
1081 prop_Merge :: Int -> Property
1083 = forValidUnitTree $ \t ->
1084 let (l,r) = split x t
1085 in valid (merge l r)
1088 {--------------------------------------------------------------------
1090 --------------------------------------------------------------------}
1091 prop_UnionValid :: Property
1093 = forValidUnitTree $ \t1 ->
1094 forValidUnitTree $ \t2 ->
1097 prop_UnionInsert :: Int -> Set Int -> Bool
1098 prop_UnionInsert x t
1099 = union t (singleton x) == insert x t
1101 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1102 prop_UnionAssoc t1 t2 t3
1103 = union t1 (union t2 t3) == union (union t1 t2) t3
1105 prop_UnionComm :: Set Int -> Set Int -> Bool
1106 prop_UnionComm t1 t2
1107 = (union t1 t2 == union t2 t1)
1111 = forValidUnitTree $ \t1 ->
1112 forValidUnitTree $ \t2 ->
1113 valid (difference t1 t2)
1115 prop_Diff :: [Int] -> [Int] -> Bool
1117 = toAscList (difference (fromList xs) (fromList ys))
1118 == List.sort ((List.\\) (nub xs) (nub ys))
1121 = forValidUnitTree $ \t1 ->
1122 forValidUnitTree $ \t2 ->
1123 valid (intersection t1 t2)
1125 prop_Int :: [Int] -> [Int] -> Bool
1127 = toAscList (intersection (fromList xs) (fromList ys))
1128 == List.sort (nub ((List.intersect) (xs) (ys)))
1130 {--------------------------------------------------------------------
1132 --------------------------------------------------------------------}
1134 = forAll (choose (5,100)) $ \n ->
1135 let xs = [0..n::Int]
1136 in fromAscList xs == fromList xs
1138 prop_List :: [Int] -> Bool
1140 = (sort (nub xs) == toList (fromList xs))
1143 {--------------------------------------------------------------------
1144 Old Data.Set compatibility interface
1145 --------------------------------------------------------------------}
1147 {-# DEPRECATED emptySet "Use empty instead" #-}
1148 -- | Obsolete equivalent of 'empty'.
1152 {-# DEPRECATED mkSet "Use fromList instead" #-}
1153 -- | Obsolete equivalent of 'fromList'.
1154 mkSet :: Ord a => [a] -> Set a
1157 {-# DEPRECATED setToList "Use elems instead." #-}
1158 -- | Obsolete equivalent of 'elems'.
1159 setToList :: Set a -> [a]
1162 {-# DEPRECATED unitSet "Use singleton instead." #-}
1163 -- | Obsolete equivalent of 'singleton'.
1164 unitSet :: a -> Set a
1167 {-# DEPRECATED elementOf "Use member instead." #-}
1168 -- | Obsolete equivalent of 'member'.
1169 elementOf :: Ord a => a -> Set a -> Bool
1172 {-# DEPRECATED isEmptySet "Use null instead." #-}
1173 -- | Obsolete equivalent of 'null'.
1174 isEmptySet :: Set a -> Bool
1177 {-# DEPRECATED cardinality "Use size instead." #-}
1178 -- | Obsolete equivalent of 'size'.
1179 cardinality :: Set a -> Int
1182 {-# DEPRECATED unionManySets "Use unions instead." #-}
1183 -- | Obsolete equivalent of 'unions'.
1184 unionManySets :: Ord a => [Set a] -> Set a
1185 unionManySets = unions
1187 {-# DEPRECATED minusSet "Use difference instead." #-}
1188 -- | Obsolete equivalent of 'difference'.
1189 minusSet :: Ord a => Set a -> Set a -> Set a
1190 minusSet = difference
1192 {-# DEPRECATED mapSet "Use map instead." #-}
1193 -- | Obsolete equivalent of 'map'.
1194 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1197 {-# DEPRECATED intersect "Use intersection instead." #-}
1198 -- | Obsolete equivalent of 'intersection'.
1199 intersect :: Ord a => Set a -> Set a -> Set a
1200 intersect = intersection
1202 {-# DEPRECATED addToSet "Use 'flip insert' instead." #-}
1203 -- | Obsolete equivalent of @'flip' 'insert'@.
1204 addToSet :: Ord a => Set a -> a -> Set a
1205 addToSet = flip insert
1207 {-# DEPRECATED delFromSet "Use `flip delete' instead." #-}
1208 -- | Obsolete equivalent of @'flip' 'delete'@.
1209 delFromSet :: Ord a => Set a -> a -> Set a
1210 delFromSet = flip delete