2 Copyright : (c) Daan Leijen 2002
4 Maintainer : libraries@haskell.org
5 Stability : provisional
8 An efficient implementation of sets.
10 This module is intended to be imported @qualified@, to avoid name
11 clashes with Prelude functions. eg.
13 > import Data.Set as Set
15 The implementation of "Set" is based on /size balanced/ binary trees (or
16 trees of /bounded balance/) as described by:
18 * Stephen Adams, \"/Efficient sets: a balancing act/\", Journal of Functional
19 Programming 3(4):553-562, October 1993, <http://www.swiss.ai.mit.edu/~adams/BB>.
21 * J. Nievergelt and E.M. Reingold, \"/Binary search trees of bounded balance/\",
22 SIAM journal of computing 2(1), March 1973.
24 Note that the implementation is /left-biased/ -- the elements of a
25 first argument are always perferred to the second, for example in
26 'union' or 'insert'. Of course, left-biasing can only be observed
27 when equality an equivalence relation instead of structural
30 ---------------------------------------------------------------------------------
33 Set -- instance Eq,Show
94 -- * Old interface, DEPRECATED
95 ,emptySet, -- :: Set a
96 mkSet, -- :: Ord a => [a] -> Set a
97 setToList, -- :: Set a -> [a]
98 unitSet, -- :: a -> Set a
99 elementOf, -- :: Ord a => a -> Set a -> Bool
100 isEmptySet, -- :: Set a -> Bool
101 cardinality, -- :: Set a -> Int
102 unionManySets, -- :: Ord a => [Set a] -> Set a
103 minusSet, -- :: Ord a => Set a -> Set a -> Set a
104 mapSet, -- :: Ord a => (b -> a) -> Set b -> Set a
105 intersect, -- :: Ord a => Set a -> Set a -> Set a
106 addToSet, -- :: Ord a => Set a -> a -> Set a
107 delFromSet, -- :: Ord a => Set a -> a -> Set a
110 import Prelude hiding (filter,foldr,foldl,null,map)
112 import qualified Data.List as List
117 import List (nub,sort)
118 import qualified List
121 {--------------------------------------------------------------------
123 --------------------------------------------------------------------}
126 -- | /O(n+m)/. See 'difference'.
127 (\\) :: Ord a => Set a -> Set a -> Set a
128 m1 \\ m2 = difference m1 m2
130 {--------------------------------------------------------------------
131 Sets are size balanced trees
132 --------------------------------------------------------------------}
133 -- | A set of values @a@.
135 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
139 {--------------------------------------------------------------------
141 --------------------------------------------------------------------}
142 -- | /O(1)/. Is this the empty set?
143 null :: Set a -> Bool
147 Bin sz x l r -> False
149 -- | /O(1)/. The number of elements in the set.
156 -- | /O(log n)/. Is the element in the set?
157 member :: Ord a => a -> Set a -> Bool
162 -> case compare x y of
167 {--------------------------------------------------------------------
169 --------------------------------------------------------------------}
170 -- | /O(1)/. The empty set.
175 -- | /O(1)/. Create a singleton set.
176 singleton :: a -> Set a
180 {--------------------------------------------------------------------
182 --------------------------------------------------------------------}
183 -- | /O(log n)/. Insert an element in a set.
184 insert :: Ord a => a -> Set a -> Set a
189 -> case compare x y of
190 LT -> balance y (insert x l) r
191 GT -> balance y l (insert x r)
195 -- | /O(log n)/. Delete an element from a set.
196 delete :: Ord a => a -> Set a -> Set a
201 -> case compare x y of
202 LT -> balance y (delete x l) r
203 GT -> balance y l (delete x r)
206 {--------------------------------------------------------------------
208 --------------------------------------------------------------------}
209 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
210 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
211 isProperSubsetOf s1 s2
212 = (size s1 < size s2) && (isSubsetOf s1 s2)
215 -- | /O(n+m)/. Is this a subset?
216 -- @(s1 `isSubsetOf` s2)@ tells whether s1 is a subset of s2.
217 isSubsetOf :: Ord a => Set a -> Set a -> Bool
219 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
221 isSubsetOfX Tip t = True
222 isSubsetOfX t Tip = False
223 isSubsetOfX (Bin _ x l r) t
224 = found && isSubsetOfX l lt && isSubsetOfX r gt
226 (found,lt,gt) = splitMember x t
229 {--------------------------------------------------------------------
231 --------------------------------------------------------------------}
232 -- | /O(log n)/. The minimal element of a set.
233 findMin :: Set a -> a
234 findMin (Bin _ x Tip r) = x
235 findMin (Bin _ x l r) = findMin l
236 findMin Tip = error "Set.findMin: empty set has no minimal element"
238 -- | /O(log n)/. The maximal element of a set.
239 findMax :: Set a -> a
240 findMax (Bin _ x l Tip) = x
241 findMax (Bin _ x l r) = findMax r
242 findMax Tip = error "Set.findMax: empty set has no maximal element"
244 -- | /O(log n)/. Delete the minimal element.
245 deleteMin :: Set a -> Set a
246 deleteMin (Bin _ x Tip r) = r
247 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
250 -- | /O(log n)/. Delete the maximal element.
251 deleteMax :: Set a -> Set a
252 deleteMax (Bin _ x l Tip) = l
253 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
257 {--------------------------------------------------------------------
259 --------------------------------------------------------------------}
260 -- | The union of a list of sets: (@unions == foldl union empty@).
261 unions :: Ord a => [Set a] -> Set a
263 = foldlStrict union empty ts
266 -- | /O(n+m)/. The union of two sets. Uses the efficient /hedge-union/ algorithm.
267 -- Hedge-union is more efficient on (bigset `union` smallset).
268 union :: Ord a => Set a -> Set a -> Set a
272 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
273 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
275 hedgeUnion cmplo cmphi t1 Tip
277 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
278 = join x (filterGt cmplo l) (filterLt cmphi r)
279 hedgeUnion cmplo cmphi (Bin _ x l r) t2
280 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
281 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
285 {--------------------------------------------------------------------
287 --------------------------------------------------------------------}
288 -- | /O(n+m)/. Difference of two sets.
289 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
290 difference :: Ord a => Set a -> Set a -> Set a
291 difference Tip t2 = Tip
292 difference t1 Tip = t1
293 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
295 hedgeDiff cmplo cmphi Tip t
297 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
298 = join x (filterGt cmplo l) (filterLt cmphi r)
299 hedgeDiff cmplo cmphi t (Bin _ x l r)
300 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
301 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
305 {--------------------------------------------------------------------
307 --------------------------------------------------------------------}
308 -- | /O(n+m)/. The intersection of two sets.
309 -- Intersection is more efficient on (bigset `intersection` smallset).
310 intersection :: Ord a => Set a -> Set a -> Set a
311 intersection Tip t = Tip
312 intersection t Tip = Tip
314 | size t1 >= size t2 = intersect' t1 t2
315 | otherwise = intersect' t2 t1
317 intersect' Tip t = Tip
318 intersect' t Tip = Tip
319 intersect' t (Bin _ x l r)
320 | found = join x tl tr
321 | otherwise = merge tl tr
323 (found,lt,gt) = splitMember x t
328 {--------------------------------------------------------------------
330 --------------------------------------------------------------------}
331 -- | /O(n)/. Filter all elements that satisfy the predicate.
332 filter :: Ord a => (a -> Bool) -> Set a -> Set a
334 filter p (Bin _ x l r)
335 | p x = join x (filter p l) (filter p r)
336 | otherwise = merge (filter p l) (filter p r)
338 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
339 -- the predicate and one with all elements that don't satisfy the predicate.
341 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
342 partition p Tip = (Tip,Tip)
343 partition p (Bin _ x l r)
344 | p x = (join x l1 r1,merge l2 r2)
345 | otherwise = (merge l1 r1,join x l2 r2)
347 (l1,l2) = partition p l
348 (r1,r2) = partition p r
350 {----------------------------------------------------------------------
352 ----------------------------------------------------------------------}
355 -- @map f s@ is the set obtained by applying @f@ to each element of @s@.
357 -- It's worth noting that the size of the result may be smaller if,
358 -- for some @(x,y)@, @x \/= y && f x == f y@
360 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
361 map f = fromList . List.map f . toList
365 -- @mapMonotonic f s == 'map' f s@, but works only when @f@ is monotonic.
366 -- /The precondition is not checked./
367 -- Semi-formally, we have:
369 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
370 -- > ==> mapMonotonic f s == map f s
371 -- > where ls = toList s
373 mapMonotonic :: (a->b) -> Set a -> Set b
374 mapMonotonic f Tip = Tip
375 mapMonotonic f (Bin sz x l r) =
376 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
379 {--------------------------------------------------------------------
381 --------------------------------------------------------------------}
382 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
383 fold :: (a -> b -> b) -> b -> Set a -> b
387 -- | /O(n)/. Post-order fold.
388 foldr :: (a -> b -> b) -> b -> Set a -> b
390 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
392 {--------------------------------------------------------------------
394 --------------------------------------------------------------------}
395 -- | /O(n)/. The elements of a set.
396 elems :: Set a -> [a]
400 {--------------------------------------------------------------------
402 --------------------------------------------------------------------}
403 -- | /O(n)/. Convert the set to an ascending list of elements.
404 toList :: Set a -> [a]
408 -- | /O(n)/. Convert the set to an ascending list of elements.
409 toAscList :: Set a -> [a]
414 -- | /O(n*log n)/. Create a set from a list of elements.
415 fromList :: Ord a => [a] -> Set a
417 = foldlStrict ins empty xs
421 {--------------------------------------------------------------------
422 Building trees from ascending/descending lists can be done in linear time.
424 Note that if [xs] is ascending that:
425 fromAscList xs == fromList xs
426 --------------------------------------------------------------------}
427 -- | /O(n)/. Build a set from an ascending list in linear time.
428 -- /The precondition (input list is ascending) is not checked./
429 fromAscList :: Eq a => [a] -> Set a
431 = fromDistinctAscList (combineEq xs)
433 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
438 (x:xx) -> combineEq' x xx
440 combineEq' z [] = [z]
442 | z==x = combineEq' z xs
443 | otherwise = z:combineEq' x xs
446 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
447 -- /The precondition (input list is strictly ascending) is not checked./
448 fromDistinctAscList :: [a] -> Set a
449 fromDistinctAscList xs
450 = build const (length xs) xs
452 -- 1) use continutations so that we use heap space instead of stack space.
453 -- 2) special case for n==5 to build bushier trees.
454 build c 0 xs = c Tip xs
455 build c 5 xs = case xs of
457 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
458 build c n xs = seq nr $ build (buildR nr c) nl xs
463 buildR n c l (x:ys) = build (buildB l x c) n ys
464 buildB l x c r zs = c (bin x l r) zs
466 {--------------------------------------------------------------------
467 Eq converts the set to a list. In a lazy setting, this
468 actually seems one of the faster methods to compare two trees
469 and it is certainly the simplest :-)
470 --------------------------------------------------------------------}
471 instance Eq a => Eq (Set a) where
472 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
474 {--------------------------------------------------------------------
476 --------------------------------------------------------------------}
478 instance Ord a => Ord (Set a) where
479 compare s1 s2 = compare (toAscList s1) (toAscList s2)
481 {--------------------------------------------------------------------
483 --------------------------------------------------------------------}
485 instance Ord a => Monoid (Set a) where
490 {--------------------------------------------------------------------
492 --------------------------------------------------------------------}
493 instance Show a => Show (Set a) where
494 showsPrec d s = showSet (toAscList s)
496 showSet :: (Show a) => [a] -> ShowS
500 = showChar '{' . shows x . showTail xs
502 showTail [] = showChar '}'
503 showTail (x:xs) = showChar ',' . shows x . showTail xs
506 {--------------------------------------------------------------------
507 Utility functions that return sub-ranges of the original
508 tree. Some functions take a comparison function as argument to
509 allow comparisons against infinite values. A function [cmplo x]
510 should be read as [compare lo x].
512 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
513 and [cmphi x == GT] for the value [x] of the root.
514 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
515 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
517 [split k t] Returns two trees [l] and [r] where all values
518 in [l] are <[k] and all keys in [r] are >[k].
519 [splitMember k t] Just like [split] but also returns whether [k]
520 was found in the tree.
521 --------------------------------------------------------------------}
523 {--------------------------------------------------------------------
524 [trim lo hi t] trims away all subtrees that surely contain no
525 values between the range [lo] to [hi]. The returned tree is either
526 empty or the key of the root is between @lo@ and @hi@.
527 --------------------------------------------------------------------}
528 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
529 trim cmplo cmphi Tip = Tip
530 trim cmplo cmphi t@(Bin sx x l r)
532 LT -> case cmphi x of
534 le -> trim cmplo cmphi l
535 ge -> trim cmplo cmphi r
537 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
538 trimMemberLo lo cmphi Tip = (False,Tip)
539 trimMemberLo lo cmphi t@(Bin sx x l r)
540 = case compare lo x of
541 LT -> case cmphi x of
542 GT -> (member lo t, t)
543 le -> trimMemberLo lo cmphi l
544 GT -> trimMemberLo lo cmphi r
545 EQ -> (True,trim (compare lo) cmphi r)
548 {--------------------------------------------------------------------
549 [filterGt x t] filter all values >[x] from tree [t]
550 [filterLt x t] filter all values <[x] from tree [t]
551 --------------------------------------------------------------------}
552 filterGt :: (a -> Ordering) -> Set a -> Set a
553 filterGt cmp Tip = Tip
554 filterGt cmp (Bin sx x l r)
556 LT -> join x (filterGt cmp l) r
560 filterLt :: (a -> Ordering) -> Set a -> Set a
561 filterLt cmp Tip = Tip
562 filterLt cmp (Bin sx x l r)
565 GT -> join x l (filterLt cmp r)
569 {--------------------------------------------------------------------
571 --------------------------------------------------------------------}
572 -- | /O(log n)/. The expression (@split x set@) is a pair @(set1,set2)@
573 -- where all elements in @set1@ are lower than @x@ and all elements in
574 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
575 split :: Ord a => a -> Set a -> (Set a,Set a)
576 split x Tip = (Tip,Tip)
577 split x (Bin sy y l r)
578 = case compare x y of
579 LT -> let (lt,gt) = split x l in (lt,join y gt r)
580 GT -> let (lt,gt) = split x r in (join y l lt,gt)
583 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
584 -- element was found in the original set.
585 splitMember :: Ord a => a -> Set a -> (Bool,Set a,Set a)
586 splitMember x Tip = (False,Tip,Tip)
587 splitMember x (Bin sy y l r)
588 = case compare x y of
589 LT -> let (found,lt,gt) = splitMember x l in (found,lt,join y gt r)
590 GT -> let (found,lt,gt) = splitMember x r in (found,join y l lt,gt)
593 {--------------------------------------------------------------------
594 Utility functions that maintain the balance properties of the tree.
595 All constructors assume that all values in [l] < [x] and all values
596 in [r] > [x], and that [l] and [r] are valid trees.
598 In order of sophistication:
599 [Bin sz x l r] The type constructor.
600 [bin x l r] Maintains the correct size, assumes that both [l]
601 and [r] are balanced with respect to each other.
602 [balance x l r] Restores the balance and size.
603 Assumes that the original tree was balanced and
604 that [l] or [r] has changed by at most one element.
605 [join x l r] Restores balance and size.
607 Furthermore, we can construct a new tree from two trees. Both operations
608 assume that all values in [l] < all values in [r] and that [l] and [r]
610 [glue l r] Glues [l] and [r] together. Assumes that [l] and
611 [r] are already balanced with respect to each other.
612 [merge l r] Merges two trees and restores balance.
614 Note: in contrast to Adam's paper, we use (<=) comparisons instead
615 of (<) comparisons in [join], [merge] and [balance].
616 Quickcheck (on [difference]) showed that this was necessary in order
617 to maintain the invariants. It is quite unsatisfactory that I haven't
618 been able to find out why this is actually the case! Fortunately, it
619 doesn't hurt to be a bit more conservative.
620 --------------------------------------------------------------------}
622 {--------------------------------------------------------------------
624 --------------------------------------------------------------------}
625 join :: a -> Set a -> Set a -> Set a
626 join x Tip r = insertMin x r
627 join x l Tip = insertMax x l
628 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
629 | delta*sizeL <= sizeR = balance z (join x l lz) rz
630 | delta*sizeR <= sizeL = balance y ly (join x ry r)
631 | otherwise = bin x l r
634 -- insertMin and insertMax don't perform potentially expensive comparisons.
635 insertMax,insertMin :: a -> Set a -> Set a
640 -> balance y l (insertMax x r)
646 -> balance y (insertMin x l) r
648 {--------------------------------------------------------------------
649 [merge l r]: merges two trees.
650 --------------------------------------------------------------------}
651 merge :: Set a -> Set a -> Set a
654 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
655 | delta*sizeL <= sizeR = balance y (merge l ly) ry
656 | delta*sizeR <= sizeL = balance x lx (merge rx r)
657 | otherwise = glue l r
659 {--------------------------------------------------------------------
660 [glue l r]: glues two trees together.
661 Assumes that [l] and [r] are already balanced with respect to each other.
662 --------------------------------------------------------------------}
663 glue :: Set a -> Set a -> Set a
667 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
668 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
671 -- | /O(log n)/. Delete and find the minimal element.
673 -- > deleteFindMin set = (findMin set, deleteMin set)
675 deleteFindMin :: Set a -> (a,Set a)
678 Bin _ x Tip r -> (x,r)
679 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
680 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
682 -- | /O(log n)/. Delete and find the maximal element.
684 -- > deleteFindMax set = (findMax set, deleteMax set)
685 deleteFindMax :: Set a -> (a,Set a)
688 Bin _ x l Tip -> (x,l)
689 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
690 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
693 {--------------------------------------------------------------------
694 [balance x l r] balances two trees with value x.
695 The sizes of the trees should balance after decreasing the
696 size of one of them. (a rotation).
698 [delta] is the maximal relative difference between the sizes of
699 two trees, it corresponds with the [w] in Adams' paper,
700 or equivalently, [1/delta] corresponds with the $\alpha$
701 in Nievergelt's paper. Adams shows that [delta] should
702 be larger than 3.745 in order to garantee that the
703 rotations can always restore balance.
705 [ratio] is the ratio between an outer and inner sibling of the
706 heavier subtree in an unbalanced setting. It determines
707 whether a double or single rotation should be performed
708 to restore balance. It is correspondes with the inverse
709 of $\alpha$ in Adam's article.
712 - [delta] should be larger than 4.646 with a [ratio] of 2.
713 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
715 - A lower [delta] leads to a more 'perfectly' balanced tree.
716 - A higher [delta] performs less rebalancing.
718 - Balancing is automatic for random data and a balancing
719 scheme is only necessary to avoid pathological worst cases.
720 Almost any choice will do in practice
722 - Allthough it seems that a rather large [delta] may perform better
723 than smaller one, measurements have shown that the smallest [delta]
724 of 4 is actually the fastest on a wide range of operations. It
725 especially improves performance on worst-case scenarios like
726 a sequence of ordered insertions.
728 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
729 to decide whether a single or double rotation is needed. Allthough
730 he actually proves that this ratio is needed to maintain the
731 invariants, his implementation uses a (invalid) ratio of 1.
732 He is aware of the problem though since he has put a comment in his
733 original source code that he doesn't care about generating a
734 slightly inbalanced tree since it doesn't seem to matter in practice.
735 However (since we use quickcheck :-) we will stick to strictly balanced
737 --------------------------------------------------------------------}
742 balance :: a -> Set a -> Set a -> Set a
744 | sizeL + sizeR <= 1 = Bin sizeX x l r
745 | sizeR >= delta*sizeL = rotateL x l r
746 | sizeL >= delta*sizeR = rotateR x l r
747 | otherwise = Bin sizeX x l r
751 sizeX = sizeL + sizeR + 1
754 rotateL x l r@(Bin _ _ ly ry)
755 | size ly < ratio*size ry = singleL x l r
756 | otherwise = doubleL x l r
758 rotateR x l@(Bin _ _ ly ry) r
759 | size ry < ratio*size ly = singleR x l r
760 | otherwise = doubleR x l r
763 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
764 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
766 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
767 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
770 {--------------------------------------------------------------------
771 The bin constructor maintains the size of the tree
772 --------------------------------------------------------------------}
773 bin :: a -> Set a -> Set a -> Set a
775 = Bin (size l + size r + 1) x l r
778 {--------------------------------------------------------------------
780 --------------------------------------------------------------------}
784 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
787 {--------------------------------------------------------------------
789 --------------------------------------------------------------------}
790 -- | /O(n)/. Show the tree that implements the set. The tree is shown
791 -- in a compressed, hanging format.
792 showTree :: Show a => Set a -> String
794 = showTreeWith True False s
797 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
798 the tree that implements the set. If @hang@ is
799 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
800 @wide@ is true, an extra wide version is shown.
802 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
809 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
820 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
832 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
833 showTreeWith hang wide t
834 | hang = (showsTreeHang wide [] t) ""
835 | otherwise = (showsTree wide [] [] t) ""
837 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
838 showsTree wide lbars rbars t
840 Tip -> showsBars lbars . showString "|\n"
842 -> showsBars lbars . shows x . showString "\n"
844 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
845 showWide wide rbars .
846 showsBars lbars . shows x . showString "\n" .
847 showWide wide lbars .
848 showsTree wide (withEmpty lbars) (withBar lbars) l
850 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
851 showsTreeHang wide bars t
853 Tip -> showsBars bars . showString "|\n"
855 -> showsBars bars . shows x . showString "\n"
857 -> showsBars bars . shows x . showString "\n" .
859 showsTreeHang wide (withBar bars) l .
861 showsTreeHang wide (withEmpty bars) r
865 | wide = showString (concat (reverse bars)) . showString "|\n"
868 showsBars :: [String] -> ShowS
872 _ -> showString (concat (reverse (tail bars))) . showString node
875 withBar bars = "| ":bars
876 withEmpty bars = " ":bars
878 {--------------------------------------------------------------------
880 --------------------------------------------------------------------}
881 -- | /O(n)/. Test if the internal set structure is valid.
882 valid :: Ord a => Set a -> Bool
884 = balanced t && ordered t && validsize t
887 = bounded (const True) (const True) t
892 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
894 balanced :: Set a -> Bool
898 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
899 balanced l && balanced r
903 = (realsize t == Just (size t))
908 Bin sz x l r -> case (realsize l,realsize r) of
909 (Just n,Just m) | n+m+1 == sz -> Just sz
913 {--------------------------------------------------------------------
915 --------------------------------------------------------------------}
916 testTree :: [Int] -> Set Int
917 testTree xs = fromList xs
918 test1 = testTree [1..20]
919 test2 = testTree [30,29..10]
920 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
922 {--------------------------------------------------------------------
924 --------------------------------------------------------------------}
929 { configMaxTest = 500
930 , configMaxFail = 5000
931 , configSize = \n -> (div n 2 + 3)
932 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
936 {--------------------------------------------------------------------
937 Arbitrary, reasonably balanced trees
938 --------------------------------------------------------------------}
939 instance (Enum a) => Arbitrary (Set a) where
940 arbitrary = sized (arbtree 0 maxkey)
943 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
945 | n <= 0 = return Tip
946 | lo >= hi = return Tip
947 | otherwise = do{ i <- choose (lo,hi)
949 ; let (ml,mr) | m==(1::Int)= (1,2)
953 ; l <- arbtree lo (i-1) (n `div` ml)
954 ; r <- arbtree (i+1) hi (n `div` mr)
955 ; return (bin (toEnum i) l r)
959 {--------------------------------------------------------------------
961 --------------------------------------------------------------------}
962 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
964 = forAll arbitrary $ \t ->
965 -- classify (balanced t) "balanced" $
966 classify (size t == 0) "empty" $
967 classify (size t > 0 && size t <= 10) "small" $
968 classify (size t > 10 && size t <= 64) "medium" $
969 classify (size t > 64) "large" $
972 forValidIntTree :: Testable a => (Set Int -> a) -> Property
976 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
982 = forValidUnitTree $ \t -> valid t
984 {--------------------------------------------------------------------
985 Single, Insert, Delete
986 --------------------------------------------------------------------}
987 prop_Single :: Int -> Bool
989 = (insert x empty == singleton x)
991 prop_InsertValid :: Int -> Property
993 = forValidUnitTree $ \t -> valid (insert k t)
995 prop_InsertDelete :: Int -> Set Int -> Property
996 prop_InsertDelete k t
997 = not (member k t) ==> delete k (insert k t) == t
999 prop_DeleteValid :: Int -> Property
1001 = forValidUnitTree $ \t ->
1002 valid (delete k (insert k t))
1004 {--------------------------------------------------------------------
1006 --------------------------------------------------------------------}
1007 prop_Join :: Int -> Property
1009 = forValidUnitTree $ \t ->
1010 let (l,r) = split x t
1011 in valid (join x l r)
1013 prop_Merge :: Int -> Property
1015 = forValidUnitTree $ \t ->
1016 let (l,r) = split x t
1017 in valid (merge l r)
1020 {--------------------------------------------------------------------
1022 --------------------------------------------------------------------}
1023 prop_UnionValid :: Property
1025 = forValidUnitTree $ \t1 ->
1026 forValidUnitTree $ \t2 ->
1029 prop_UnionInsert :: Int -> Set Int -> Bool
1030 prop_UnionInsert x t
1031 = union t (singleton x) == insert x t
1033 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1034 prop_UnionAssoc t1 t2 t3
1035 = union t1 (union t2 t3) == union (union t1 t2) t3
1037 prop_UnionComm :: Set Int -> Set Int -> Bool
1038 prop_UnionComm t1 t2
1039 = (union t1 t2 == union t2 t1)
1043 = forValidUnitTree $ \t1 ->
1044 forValidUnitTree $ \t2 ->
1045 valid (difference t1 t2)
1047 prop_Diff :: [Int] -> [Int] -> Bool
1049 = toAscList (difference (fromList xs) (fromList ys))
1050 == List.sort ((List.\\) (nub xs) (nub ys))
1053 = forValidUnitTree $ \t1 ->
1054 forValidUnitTree $ \t2 ->
1055 valid (intersection t1 t2)
1057 prop_Int :: [Int] -> [Int] -> Bool
1059 = toAscList (intersection (fromList xs) (fromList ys))
1060 == List.sort (nub ((List.intersect) (xs) (ys)))
1062 {--------------------------------------------------------------------
1064 --------------------------------------------------------------------}
1066 = forAll (choose (5,100)) $ \n ->
1067 let xs = [0..n::Int]
1068 in fromAscList xs == fromList xs
1070 prop_List :: [Int] -> Bool
1072 = (sort (nub xs) == toList (fromList xs))
1075 {--------------------------------------------------------------------
1076 Old Data.Set compatibility interface
1077 --------------------------------------------------------------------}
1079 {-# DEPRECATED emptySet "Use empty instead" #-}
1083 {-# DEPRECATED mkSet "Equivalent to 'foldl insert empty'." #-}
1084 mkSet :: Ord a => [a] -> Set a
1085 mkSet = List.foldl' (flip insert) empty
1087 {-# DEPRECATED setToList "Use instead." #-}
1088 setToList :: Set a -> [a]
1091 {-# DEPRECATED unitSet "Use singleton instead." #-}
1092 unitSet :: a -> Set a
1095 {-# DEPRECATED elementOf "Use member instead." #-}
1096 elementOf :: Ord a => a -> Set a -> Bool
1099 {-# DEPRECATED isEmptySet "Use null instead." #-}
1100 isEmptySet :: Set a -> Bool
1103 {-# DEPRECATED cardinality "Use size instead." #-}
1104 cardinality :: Set a -> Int
1107 {-# DEPRECATED unionManySets "Use unions instead." #-}
1108 unionManySets :: Ord a => [Set a] -> Set a
1109 unionManySets = unions
1111 {-# DEPRECATED minusSet "Use difference instead." #-}
1112 minusSet :: Ord a => Set a -> Set a -> Set a
1113 minusSet = difference
1115 {-# DEPRECATED mapSet "Use map instead." #-}
1116 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1119 {-# DEPRECATED intersect "Use intersection instead." #-}
1120 intersect :: Ord a => Set a -> Set a -> Set a
1121 intersect = intersection
1123 {-# DEPRECATED addToSet "Use insert instead." #-}
1124 addToSet :: Ord a => Set a -> a -> Set a
1125 addToSet = flip insert
1127 {-# DEPRECATED delFromSet "Use delete instead." #-}
1128 delFromSet :: Ord a => Set a -> a -> Set a
1129 delFromSet = flip delete