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,foldl,null,map)
116 import qualified Data.List as List
122 import List (nub,sort)
123 import qualified List
126 {--------------------------------------------------------------------
128 --------------------------------------------------------------------}
131 -- | /O(n+m)/. See 'difference'.
132 (\\) :: Ord a => Set a -> Set a -> Set a
133 m1 \\ m2 = difference m1 m2
135 {--------------------------------------------------------------------
136 Sets are size balanced trees
137 --------------------------------------------------------------------}
138 -- | A set of values @a@.
140 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
144 {--------------------------------------------------------------------
146 --------------------------------------------------------------------}
147 -- | /O(1)/. Is this the empty set?
148 null :: Set a -> Bool
152 Bin sz x l r -> False
154 -- | /O(1)/. The number of elements in the set.
161 -- | /O(log n)/. Is the element in the set?
162 member :: Ord a => a -> Set a -> Bool
167 -> case compare x y of
172 {--------------------------------------------------------------------
174 --------------------------------------------------------------------}
175 -- | /O(1)/. The empty set.
180 -- | /O(1)/. Create a singleton set.
181 singleton :: a -> Set a
185 {--------------------------------------------------------------------
187 --------------------------------------------------------------------}
188 -- | /O(log n)/. Insert an element in a set.
189 insert :: Ord a => a -> Set a -> Set a
194 -> case compare x y of
195 LT -> balance y (insert x l) r
196 GT -> balance y l (insert x r)
200 -- | /O(log n)/. Delete an element from a set.
201 delete :: Ord a => a -> Set a -> Set a
206 -> case compare x y of
207 LT -> balance y (delete x l) r
208 GT -> balance y l (delete x r)
211 {--------------------------------------------------------------------
213 --------------------------------------------------------------------}
214 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
215 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
216 isProperSubsetOf s1 s2
217 = (size s1 < size s2) && (isSubsetOf s1 s2)
220 -- | /O(n+m)/. Is this a subset?
221 -- @(s1 `isSubsetOf` s2)@ tells whether s1 is a subset of s2.
222 isSubsetOf :: Ord a => Set a -> Set a -> Bool
224 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
226 isSubsetOfX Tip t = True
227 isSubsetOfX t Tip = False
228 isSubsetOfX (Bin _ x l r) t
229 = found && isSubsetOfX l lt && isSubsetOfX r gt
231 (found,lt,gt) = splitMember x t
234 {--------------------------------------------------------------------
236 --------------------------------------------------------------------}
237 -- | /O(log n)/. The minimal element of a set.
238 findMin :: Set a -> a
239 findMin (Bin _ x Tip r) = x
240 findMin (Bin _ x l r) = findMin l
241 findMin Tip = error "Set.findMin: empty set has no minimal element"
243 -- | /O(log n)/. The maximal element of a set.
244 findMax :: Set a -> a
245 findMax (Bin _ x l Tip) = x
246 findMax (Bin _ x l r) = findMax r
247 findMax Tip = error "Set.findMax: empty set has no maximal element"
249 -- | /O(log n)/. Delete the minimal element.
250 deleteMin :: Set a -> Set a
251 deleteMin (Bin _ x Tip r) = r
252 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
255 -- | /O(log n)/. Delete the maximal element.
256 deleteMax :: Set a -> Set a
257 deleteMax (Bin _ x l Tip) = l
258 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
262 {--------------------------------------------------------------------
264 --------------------------------------------------------------------}
265 -- | The union of a list of sets: (@unions == foldl union empty@).
266 unions :: Ord a => [Set a] -> Set a
268 = foldlStrict union empty ts
271 -- | /O(n+m)/. The union of two sets. Uses the efficient /hedge-union/ algorithm.
272 -- Hedge-union is more efficient on (bigset `union` smallset).
273 union :: Ord a => Set a -> Set a -> Set a
277 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
278 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
280 hedgeUnion cmplo cmphi t1 Tip
282 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
283 = join x (filterGt cmplo l) (filterLt cmphi r)
284 hedgeUnion cmplo cmphi (Bin _ x l r) t2
285 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
286 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
290 {--------------------------------------------------------------------
292 --------------------------------------------------------------------}
293 -- | /O(n+m)/. Difference of two sets.
294 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
295 difference :: Ord a => Set a -> Set a -> Set a
296 difference Tip t2 = Tip
297 difference t1 Tip = t1
298 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
300 hedgeDiff cmplo cmphi Tip t
302 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
303 = join x (filterGt cmplo l) (filterLt cmphi r)
304 hedgeDiff cmplo cmphi t (Bin _ x l r)
305 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
306 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
310 {--------------------------------------------------------------------
312 --------------------------------------------------------------------}
313 -- | /O(n+m)/. The intersection of two sets.
314 -- Intersection is more efficient on (bigset `intersection` smallset).
315 intersection :: Ord a => Set a -> Set a -> Set a
316 intersection Tip t = Tip
317 intersection t Tip = Tip
319 | size t1 >= size t2 = intersect' t1 t2
320 | otherwise = intersect' t2 t1
322 intersect' Tip t = Tip
323 intersect' t Tip = Tip
324 intersect' t (Bin _ x l r)
325 | found = join x tl tr
326 | otherwise = merge tl tr
328 (found,lt,gt) = splitMember x t
333 {--------------------------------------------------------------------
335 --------------------------------------------------------------------}
336 -- | /O(n)/. Filter all elements that satisfy the predicate.
337 filter :: Ord a => (a -> Bool) -> Set a -> Set a
339 filter p (Bin _ x l r)
340 | p x = join x (filter p l) (filter p r)
341 | otherwise = merge (filter p l) (filter p r)
343 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
344 -- the predicate and one with all elements that don't satisfy the predicate.
346 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
347 partition p Tip = (Tip,Tip)
348 partition p (Bin _ x l r)
349 | p x = (join x l1 r1,merge l2 r2)
350 | otherwise = (merge l1 r1,join x l2 r2)
352 (l1,l2) = partition p l
353 (r1,r2) = partition p r
355 {----------------------------------------------------------------------
357 ----------------------------------------------------------------------}
360 -- @map f s@ is the set obtained by applying @f@ to each element of @s@.
362 -- It's worth noting that the size of the result may be smaller if,
363 -- for some @(x,y)@, @x \/= y && f x == f y@
365 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
366 map f = fromList . List.map f . toList
370 -- @mapMonotonic f s == 'map' f s@, but works only when @f@ is monotonic.
371 -- /The precondition is not checked./
372 -- Semi-formally, we have:
374 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
375 -- > ==> mapMonotonic f s == map f s
376 -- > where ls = toList s
378 mapMonotonic :: (a->b) -> Set a -> Set b
379 mapMonotonic f Tip = Tip
380 mapMonotonic f (Bin sz x l r) =
381 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
384 {--------------------------------------------------------------------
386 --------------------------------------------------------------------}
387 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
388 fold :: (a -> b -> b) -> b -> Set a -> b
392 -- | /O(n)/. Post-order fold.
393 foldr :: (a -> b -> b) -> b -> Set a -> b
395 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
397 {--------------------------------------------------------------------
399 --------------------------------------------------------------------}
400 -- | /O(n)/. The elements of a set.
401 elems :: Set a -> [a]
405 {--------------------------------------------------------------------
407 --------------------------------------------------------------------}
408 -- | /O(n)/. Convert the set to an ascending list of elements.
409 toList :: Set a -> [a]
413 -- | /O(n)/. Convert the set to an ascending list of elements.
414 toAscList :: Set a -> [a]
419 -- | /O(n*log n)/. Create a set from a list of elements.
420 fromList :: Ord a => [a] -> Set a
422 = foldlStrict ins empty xs
426 {--------------------------------------------------------------------
427 Building trees from ascending/descending lists can be done in linear time.
429 Note that if [xs] is ascending that:
430 fromAscList xs == fromList xs
431 --------------------------------------------------------------------}
432 -- | /O(n)/. Build a set from an ascending list in linear time.
433 -- /The precondition (input list is ascending) is not checked./
434 fromAscList :: Eq a => [a] -> Set a
436 = fromDistinctAscList (combineEq xs)
438 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
443 (x:xx) -> combineEq' x xx
445 combineEq' z [] = [z]
447 | z==x = combineEq' z xs
448 | otherwise = z:combineEq' x xs
451 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
452 -- /The precondition (input list is strictly ascending) is not checked./
453 fromDistinctAscList :: [a] -> Set a
454 fromDistinctAscList xs
455 = build const (length xs) xs
457 -- 1) use continutations so that we use heap space instead of stack space.
458 -- 2) special case for n==5 to build bushier trees.
459 build c 0 xs = c Tip xs
460 build c 5 xs = case xs of
462 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
463 build c n xs = seq nr $ build (buildR nr c) nl xs
468 buildR n c l (x:ys) = build (buildB l x c) n ys
469 buildB l x c r zs = c (bin x l r) zs
471 {--------------------------------------------------------------------
472 Eq converts the set to a list. In a lazy setting, this
473 actually seems one of the faster methods to compare two trees
474 and it is certainly the simplest :-)
475 --------------------------------------------------------------------}
476 instance Eq a => Eq (Set a) where
477 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
479 {--------------------------------------------------------------------
481 --------------------------------------------------------------------}
483 instance Ord a => Ord (Set a) where
484 compare s1 s2 = compare (toAscList s1) (toAscList s2)
486 {--------------------------------------------------------------------
488 --------------------------------------------------------------------}
490 instance Ord a => Monoid (Set a) where
495 {--------------------------------------------------------------------
497 --------------------------------------------------------------------}
498 instance Show a => Show (Set a) where
499 showsPrec d s = showSet (toAscList s)
501 showSet :: (Show a) => [a] -> ShowS
505 = showChar '{' . shows x . showTail xs
507 showTail [] = showChar '}'
508 showTail (x:xs) = showChar ',' . shows x . showTail xs
511 {--------------------------------------------------------------------
513 --------------------------------------------------------------------}
515 #include "Typeable.h"
516 INSTANCE_TYPEABLE1(Set,setTc,"Set")
518 {--------------------------------------------------------------------
519 Utility functions that return sub-ranges of the original
520 tree. Some functions take a comparison function as argument to
521 allow comparisons against infinite values. A function [cmplo x]
522 should be read as [compare lo x].
524 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
525 and [cmphi x == GT] for the value [x] of the root.
526 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
527 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
529 [split k t] Returns two trees [l] and [r] where all values
530 in [l] are <[k] and all keys in [r] are >[k].
531 [splitMember k t] Just like [split] but also returns whether [k]
532 was found in the tree.
533 --------------------------------------------------------------------}
535 {--------------------------------------------------------------------
536 [trim lo hi t] trims away all subtrees that surely contain no
537 values between the range [lo] to [hi]. The returned tree is either
538 empty or the key of the root is between @lo@ and @hi@.
539 --------------------------------------------------------------------}
540 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
541 trim cmplo cmphi Tip = Tip
542 trim cmplo cmphi t@(Bin sx x l r)
544 LT -> case cmphi x of
546 le -> trim cmplo cmphi l
547 ge -> trim cmplo cmphi r
549 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
550 trimMemberLo lo cmphi Tip = (False,Tip)
551 trimMemberLo lo cmphi t@(Bin sx x l r)
552 = case compare lo x of
553 LT -> case cmphi x of
554 GT -> (member lo t, t)
555 le -> trimMemberLo lo cmphi l
556 GT -> trimMemberLo lo cmphi r
557 EQ -> (True,trim (compare lo) cmphi r)
560 {--------------------------------------------------------------------
561 [filterGt x t] filter all values >[x] from tree [t]
562 [filterLt x t] filter all values <[x] from tree [t]
563 --------------------------------------------------------------------}
564 filterGt :: (a -> Ordering) -> Set a -> Set a
565 filterGt cmp Tip = Tip
566 filterGt cmp (Bin sx x l r)
568 LT -> join x (filterGt cmp l) r
572 filterLt :: (a -> Ordering) -> Set a -> Set a
573 filterLt cmp Tip = Tip
574 filterLt cmp (Bin sx x l r)
577 GT -> join x l (filterLt cmp r)
581 {--------------------------------------------------------------------
583 --------------------------------------------------------------------}
584 -- | /O(log n)/. The expression (@split x set@) is a pair @(set1,set2)@
585 -- where all elements in @set1@ are lower than @x@ and all elements in
586 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
587 split :: Ord a => a -> Set a -> (Set a,Set a)
588 split x Tip = (Tip,Tip)
589 split x (Bin sy y l r)
590 = case compare x y of
591 LT -> let (lt,gt) = split x l in (lt,join y gt r)
592 GT -> let (lt,gt) = split x r in (join y l lt,gt)
595 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
596 -- element was found in the original set.
597 splitMember :: Ord a => a -> Set a -> (Bool,Set a,Set a)
598 splitMember x Tip = (False,Tip,Tip)
599 splitMember x (Bin sy y l r)
600 = case compare x y of
601 LT -> let (found,lt,gt) = splitMember x l in (found,lt,join y gt r)
602 GT -> let (found,lt,gt) = splitMember x r in (found,join y l lt,gt)
605 {--------------------------------------------------------------------
606 Utility functions that maintain the balance properties of the tree.
607 All constructors assume that all values in [l] < [x] and all values
608 in [r] > [x], and that [l] and [r] are valid trees.
610 In order of sophistication:
611 [Bin sz x l r] The type constructor.
612 [bin x l r] Maintains the correct size, assumes that both [l]
613 and [r] are balanced with respect to each other.
614 [balance x l r] Restores the balance and size.
615 Assumes that the original tree was balanced and
616 that [l] or [r] has changed by at most one element.
617 [join x l r] Restores balance and size.
619 Furthermore, we can construct a new tree from two trees. Both operations
620 assume that all values in [l] < all values in [r] and that [l] and [r]
622 [glue l r] Glues [l] and [r] together. Assumes that [l] and
623 [r] are already balanced with respect to each other.
624 [merge l r] Merges two trees and restores balance.
626 Note: in contrast to Adam's paper, we use (<=) comparisons instead
627 of (<) comparisons in [join], [merge] and [balance].
628 Quickcheck (on [difference]) showed that this was necessary in order
629 to maintain the invariants. It is quite unsatisfactory that I haven't
630 been able to find out why this is actually the case! Fortunately, it
631 doesn't hurt to be a bit more conservative.
632 --------------------------------------------------------------------}
634 {--------------------------------------------------------------------
636 --------------------------------------------------------------------}
637 join :: a -> Set a -> Set a -> Set a
638 join x Tip r = insertMin x r
639 join x l Tip = insertMax x l
640 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
641 | delta*sizeL <= sizeR = balance z (join x l lz) rz
642 | delta*sizeR <= sizeL = balance y ly (join x ry r)
643 | otherwise = bin x l r
646 -- insertMin and insertMax don't perform potentially expensive comparisons.
647 insertMax,insertMin :: a -> Set a -> Set a
652 -> balance y l (insertMax x r)
658 -> balance y (insertMin x l) r
660 {--------------------------------------------------------------------
661 [merge l r]: merges two trees.
662 --------------------------------------------------------------------}
663 merge :: Set a -> Set a -> Set a
666 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
667 | delta*sizeL <= sizeR = balance y (merge l ly) ry
668 | delta*sizeR <= sizeL = balance x lx (merge rx r)
669 | otherwise = glue l r
671 {--------------------------------------------------------------------
672 [glue l r]: glues two trees together.
673 Assumes that [l] and [r] are already balanced with respect to each other.
674 --------------------------------------------------------------------}
675 glue :: Set a -> Set a -> Set a
679 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
680 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
683 -- | /O(log n)/. Delete and find the minimal element.
685 -- > deleteFindMin set = (findMin set, deleteMin set)
687 deleteFindMin :: Set a -> (a,Set a)
690 Bin _ x Tip r -> (x,r)
691 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
692 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
694 -- | /O(log n)/. Delete and find the maximal element.
696 -- > deleteFindMax set = (findMax set, deleteMax set)
697 deleteFindMax :: Set a -> (a,Set a)
700 Bin _ x l Tip -> (x,l)
701 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
702 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
705 {--------------------------------------------------------------------
706 [balance x l r] balances two trees with value x.
707 The sizes of the trees should balance after decreasing the
708 size of one of them. (a rotation).
710 [delta] is the maximal relative difference between the sizes of
711 two trees, it corresponds with the [w] in Adams' paper,
712 or equivalently, [1/delta] corresponds with the $\alpha$
713 in Nievergelt's paper. Adams shows that [delta] should
714 be larger than 3.745 in order to garantee that the
715 rotations can always restore balance.
717 [ratio] is the ratio between an outer and inner sibling of the
718 heavier subtree in an unbalanced setting. It determines
719 whether a double or single rotation should be performed
720 to restore balance. It is correspondes with the inverse
721 of $\alpha$ in Adam's article.
724 - [delta] should be larger than 4.646 with a [ratio] of 2.
725 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
727 - A lower [delta] leads to a more 'perfectly' balanced tree.
728 - A higher [delta] performs less rebalancing.
730 - Balancing is automatic for random data and a balancing
731 scheme is only necessary to avoid pathological worst cases.
732 Almost any choice will do in practice
734 - Allthough it seems that a rather large [delta] may perform better
735 than smaller one, measurements have shown that the smallest [delta]
736 of 4 is actually the fastest on a wide range of operations. It
737 especially improves performance on worst-case scenarios like
738 a sequence of ordered insertions.
740 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
741 to decide whether a single or double rotation is needed. Allthough
742 he actually proves that this ratio is needed to maintain the
743 invariants, his implementation uses a (invalid) ratio of 1.
744 He is aware of the problem though since he has put a comment in his
745 original source code that he doesn't care about generating a
746 slightly inbalanced tree since it doesn't seem to matter in practice.
747 However (since we use quickcheck :-) we will stick to strictly balanced
749 --------------------------------------------------------------------}
754 balance :: a -> Set a -> Set a -> Set a
756 | sizeL + sizeR <= 1 = Bin sizeX x l r
757 | sizeR >= delta*sizeL = rotateL x l r
758 | sizeL >= delta*sizeR = rotateR x l r
759 | otherwise = Bin sizeX x l r
763 sizeX = sizeL + sizeR + 1
766 rotateL x l r@(Bin _ _ ly ry)
767 | size ly < ratio*size ry = singleL x l r
768 | otherwise = doubleL x l r
770 rotateR x l@(Bin _ _ ly ry) r
771 | size ry < ratio*size ly = singleR x l r
772 | otherwise = doubleR x l r
775 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
776 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
778 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
779 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
782 {--------------------------------------------------------------------
783 The bin constructor maintains the size of the tree
784 --------------------------------------------------------------------}
785 bin :: a -> Set a -> Set a -> Set a
787 = Bin (size l + size r + 1) x l r
790 {--------------------------------------------------------------------
792 --------------------------------------------------------------------}
796 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
799 {--------------------------------------------------------------------
801 --------------------------------------------------------------------}
802 -- | /O(n)/. Show the tree that implements the set. The tree is shown
803 -- in a compressed, hanging format.
804 showTree :: Show a => Set a -> String
806 = showTreeWith True False s
809 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
810 the tree that implements the set. If @hang@ is
811 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
812 @wide@ is true, an extra wide version is shown.
814 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
821 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
832 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
844 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
845 showTreeWith hang wide t
846 | hang = (showsTreeHang wide [] t) ""
847 | otherwise = (showsTree wide [] [] t) ""
849 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
850 showsTree wide lbars rbars t
852 Tip -> showsBars lbars . showString "|\n"
854 -> showsBars lbars . shows x . showString "\n"
856 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
857 showWide wide rbars .
858 showsBars lbars . shows x . showString "\n" .
859 showWide wide lbars .
860 showsTree wide (withEmpty lbars) (withBar lbars) l
862 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
863 showsTreeHang wide bars t
865 Tip -> showsBars bars . showString "|\n"
867 -> showsBars bars . shows x . showString "\n"
869 -> showsBars bars . shows x . showString "\n" .
871 showsTreeHang wide (withBar bars) l .
873 showsTreeHang wide (withEmpty bars) r
877 | wide = showString (concat (reverse bars)) . showString "|\n"
880 showsBars :: [String] -> ShowS
884 _ -> showString (concat (reverse (tail bars))) . showString node
887 withBar bars = "| ":bars
888 withEmpty bars = " ":bars
890 {--------------------------------------------------------------------
892 --------------------------------------------------------------------}
893 -- | /O(n)/. Test if the internal set structure is valid.
894 valid :: Ord a => Set a -> Bool
896 = balanced t && ordered t && validsize t
899 = bounded (const True) (const True) t
904 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
906 balanced :: Set a -> Bool
910 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
911 balanced l && balanced r
915 = (realsize t == Just (size t))
920 Bin sz x l r -> case (realsize l,realsize r) of
921 (Just n,Just m) | n+m+1 == sz -> Just sz
925 {--------------------------------------------------------------------
927 --------------------------------------------------------------------}
928 testTree :: [Int] -> Set Int
929 testTree xs = fromList xs
930 test1 = testTree [1..20]
931 test2 = testTree [30,29..10]
932 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
934 {--------------------------------------------------------------------
936 --------------------------------------------------------------------}
941 { configMaxTest = 500
942 , configMaxFail = 5000
943 , configSize = \n -> (div n 2 + 3)
944 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
948 {--------------------------------------------------------------------
949 Arbitrary, reasonably balanced trees
950 --------------------------------------------------------------------}
951 instance (Enum a) => Arbitrary (Set a) where
952 arbitrary = sized (arbtree 0 maxkey)
955 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
957 | n <= 0 = return Tip
958 | lo >= hi = return Tip
959 | otherwise = do{ i <- choose (lo,hi)
961 ; let (ml,mr) | m==(1::Int)= (1,2)
965 ; l <- arbtree lo (i-1) (n `div` ml)
966 ; r <- arbtree (i+1) hi (n `div` mr)
967 ; return (bin (toEnum i) l r)
971 {--------------------------------------------------------------------
973 --------------------------------------------------------------------}
974 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
976 = forAll arbitrary $ \t ->
977 -- classify (balanced t) "balanced" $
978 classify (size t == 0) "empty" $
979 classify (size t > 0 && size t <= 10) "small" $
980 classify (size t > 10 && size t <= 64) "medium" $
981 classify (size t > 64) "large" $
984 forValidIntTree :: Testable a => (Set Int -> a) -> Property
988 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
994 = forValidUnitTree $ \t -> valid t
996 {--------------------------------------------------------------------
997 Single, Insert, Delete
998 --------------------------------------------------------------------}
999 prop_Single :: Int -> Bool
1001 = (insert x empty == singleton x)
1003 prop_InsertValid :: Int -> Property
1005 = forValidUnitTree $ \t -> valid (insert k t)
1007 prop_InsertDelete :: Int -> Set Int -> Property
1008 prop_InsertDelete k t
1009 = not (member k t) ==> delete k (insert k t) == t
1011 prop_DeleteValid :: Int -> Property
1013 = forValidUnitTree $ \t ->
1014 valid (delete k (insert k t))
1016 {--------------------------------------------------------------------
1018 --------------------------------------------------------------------}
1019 prop_Join :: Int -> Property
1021 = forValidUnitTree $ \t ->
1022 let (l,r) = split x t
1023 in valid (join x l r)
1025 prop_Merge :: Int -> Property
1027 = forValidUnitTree $ \t ->
1028 let (l,r) = split x t
1029 in valid (merge l r)
1032 {--------------------------------------------------------------------
1034 --------------------------------------------------------------------}
1035 prop_UnionValid :: Property
1037 = forValidUnitTree $ \t1 ->
1038 forValidUnitTree $ \t2 ->
1041 prop_UnionInsert :: Int -> Set Int -> Bool
1042 prop_UnionInsert x t
1043 = union t (singleton x) == insert x t
1045 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1046 prop_UnionAssoc t1 t2 t3
1047 = union t1 (union t2 t3) == union (union t1 t2) t3
1049 prop_UnionComm :: Set Int -> Set Int -> Bool
1050 prop_UnionComm t1 t2
1051 = (union t1 t2 == union t2 t1)
1055 = forValidUnitTree $ \t1 ->
1056 forValidUnitTree $ \t2 ->
1057 valid (difference t1 t2)
1059 prop_Diff :: [Int] -> [Int] -> Bool
1061 = toAscList (difference (fromList xs) (fromList ys))
1062 == List.sort ((List.\\) (nub xs) (nub ys))
1065 = forValidUnitTree $ \t1 ->
1066 forValidUnitTree $ \t2 ->
1067 valid (intersection t1 t2)
1069 prop_Int :: [Int] -> [Int] -> Bool
1071 = toAscList (intersection (fromList xs) (fromList ys))
1072 == List.sort (nub ((List.intersect) (xs) (ys)))
1074 {--------------------------------------------------------------------
1076 --------------------------------------------------------------------}
1078 = forAll (choose (5,100)) $ \n ->
1079 let xs = [0..n::Int]
1080 in fromAscList xs == fromList xs
1082 prop_List :: [Int] -> Bool
1084 = (sort (nub xs) == toList (fromList xs))
1087 {--------------------------------------------------------------------
1088 Old Data.Set compatibility interface
1089 --------------------------------------------------------------------}
1091 {-# DEPRECATED emptySet "Use empty instead" #-}
1095 {-# DEPRECATED mkSet "Equivalent to 'foldl' (flip insert) empty'." #-}
1096 mkSet :: Ord a => [a] -> Set a
1097 mkSet = List.foldl' (flip insert) empty
1099 {-# DEPRECATED setToList "Use elems instead." #-}
1100 setToList :: Set a -> [a]
1103 {-# DEPRECATED unitSet "Use singleton instead." #-}
1104 unitSet :: a -> Set a
1107 {-# DEPRECATED elementOf "Use member instead." #-}
1108 elementOf :: Ord a => a -> Set a -> Bool
1111 {-# DEPRECATED isEmptySet "Use null instead." #-}
1112 isEmptySet :: Set a -> Bool
1115 {-# DEPRECATED cardinality "Use size instead." #-}
1116 cardinality :: Set a -> Int
1119 {-# DEPRECATED unionManySets "Use unions instead." #-}
1120 unionManySets :: Ord a => [Set a] -> Set a
1121 unionManySets = unions
1123 {-# DEPRECATED minusSet "Use difference instead." #-}
1124 minusSet :: Ord a => Set a -> Set a -> Set a
1125 minusSet = difference
1127 {-# DEPRECATED mapSet "Use map instead." #-}
1128 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1131 {-# DEPRECATED intersect "Use intersection instead." #-}
1132 intersect :: Ord a => Set a -> Set a -> Set a
1133 intersect = intersection
1135 {-# DEPRECATED addToSet "Use 'flip insert' instead." #-}
1136 addToSet :: Ord a => Set a -> a -> Set a
1137 addToSet = flip insert
1139 {-# DEPRECATED delFromSet "Use `flip delete' instead." #-}
1140 delFromSet :: Ord a => Set a -> a -> Set a
1141 delFromSet = flip delete