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
121 import List (nub,sort)
122 import qualified List
125 {--------------------------------------------------------------------
127 --------------------------------------------------------------------}
130 -- | /O(n+m)/. See 'difference'.
131 (\\) :: Ord a => Set a -> Set a -> Set a
132 m1 \\ m2 = difference m1 m2
134 {--------------------------------------------------------------------
135 Sets are size balanced trees
136 --------------------------------------------------------------------}
137 -- | A set of values @a@.
139 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
143 {--------------------------------------------------------------------
145 --------------------------------------------------------------------}
146 -- | /O(1)/. Is this the empty set?
147 null :: Set a -> Bool
151 Bin sz x l r -> False
153 -- | /O(1)/. The number of elements in the set.
160 -- | /O(log n)/. Is the element in the set?
161 member :: Ord a => a -> Set a -> Bool
166 -> case compare x y of
171 {--------------------------------------------------------------------
173 --------------------------------------------------------------------}
174 -- | /O(1)/. The empty set.
179 -- | /O(1)/. Create a singleton set.
180 singleton :: a -> Set a
184 {--------------------------------------------------------------------
186 --------------------------------------------------------------------}
187 -- | /O(log n)/. Insert an element in a set.
188 insert :: Ord a => a -> Set a -> Set a
193 -> case compare x y of
194 LT -> balance y (insert x l) r
195 GT -> balance y l (insert x r)
199 -- | /O(log n)/. Delete an element from a set.
200 delete :: Ord a => a -> Set a -> Set a
205 -> case compare x y of
206 LT -> balance y (delete x l) r
207 GT -> balance y l (delete x r)
210 {--------------------------------------------------------------------
212 --------------------------------------------------------------------}
213 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
214 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
215 isProperSubsetOf s1 s2
216 = (size s1 < size s2) && (isSubsetOf s1 s2)
219 -- | /O(n+m)/. Is this a subset?
220 -- @(s1 `isSubsetOf` s2)@ tells whether s1 is a subset of s2.
221 isSubsetOf :: Ord a => Set a -> Set a -> Bool
223 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
225 isSubsetOfX Tip t = True
226 isSubsetOfX t Tip = False
227 isSubsetOfX (Bin _ x l r) t
228 = found && isSubsetOfX l lt && isSubsetOfX r gt
230 (found,lt,gt) = splitMember x t
233 {--------------------------------------------------------------------
235 --------------------------------------------------------------------}
236 -- | /O(log n)/. The minimal element of a set.
237 findMin :: Set a -> a
238 findMin (Bin _ x Tip r) = x
239 findMin (Bin _ x l r) = findMin l
240 findMin Tip = error "Set.findMin: empty set has no minimal element"
242 -- | /O(log n)/. The maximal element of a set.
243 findMax :: Set a -> a
244 findMax (Bin _ x l Tip) = x
245 findMax (Bin _ x l r) = findMax r
246 findMax Tip = error "Set.findMax: empty set has no maximal element"
248 -- | /O(log n)/. Delete the minimal element.
249 deleteMin :: Set a -> Set a
250 deleteMin (Bin _ x Tip r) = r
251 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
254 -- | /O(log n)/. Delete the maximal element.
255 deleteMax :: Set a -> Set a
256 deleteMax (Bin _ x l Tip) = l
257 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
261 {--------------------------------------------------------------------
263 --------------------------------------------------------------------}
264 -- | The union of a list of sets: (@unions == foldl union empty@).
265 unions :: Ord a => [Set a] -> Set a
267 = foldlStrict union empty ts
270 -- | /O(n+m)/. The union of two sets. Uses the efficient /hedge-union/ algorithm.
271 -- Hedge-union is more efficient on (bigset `union` smallset).
272 union :: Ord a => Set a -> Set a -> Set a
276 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
277 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
279 hedgeUnion cmplo cmphi t1 Tip
281 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
282 = join x (filterGt cmplo l) (filterLt cmphi r)
283 hedgeUnion cmplo cmphi (Bin _ x l r) t2
284 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
285 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
289 {--------------------------------------------------------------------
291 --------------------------------------------------------------------}
292 -- | /O(n+m)/. Difference of two sets.
293 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
294 difference :: Ord a => Set a -> Set a -> Set a
295 difference Tip t2 = Tip
296 difference t1 Tip = t1
297 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
299 hedgeDiff cmplo cmphi Tip t
301 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
302 = join x (filterGt cmplo l) (filterLt cmphi r)
303 hedgeDiff cmplo cmphi t (Bin _ x l r)
304 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
305 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
309 {--------------------------------------------------------------------
311 --------------------------------------------------------------------}
312 -- | /O(n+m)/. The intersection of two sets.
313 -- Intersection is more efficient on (bigset `intersection` smallset).
314 intersection :: Ord a => Set a -> Set a -> Set a
315 intersection Tip t = Tip
316 intersection t Tip = Tip
318 | size t1 >= size t2 = intersect' t1 t2
319 | otherwise = intersect' t2 t1
321 intersect' Tip t = Tip
322 intersect' t Tip = Tip
323 intersect' t (Bin _ x l r)
324 | found = join x tl tr
325 | otherwise = merge tl tr
327 (found,lt,gt) = splitMember x t
332 {--------------------------------------------------------------------
334 --------------------------------------------------------------------}
335 -- | /O(n)/. Filter all elements that satisfy the predicate.
336 filter :: Ord a => (a -> Bool) -> Set a -> Set a
338 filter p (Bin _ x l r)
339 | p x = join x (filter p l) (filter p r)
340 | otherwise = merge (filter p l) (filter p r)
342 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
343 -- the predicate and one with all elements that don't satisfy the predicate.
345 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
346 partition p Tip = (Tip,Tip)
347 partition p (Bin _ x l r)
348 | p x = (join x l1 r1,merge l2 r2)
349 | otherwise = (merge l1 r1,join x l2 r2)
351 (l1,l2) = partition p l
352 (r1,r2) = partition p r
354 {----------------------------------------------------------------------
356 ----------------------------------------------------------------------}
359 -- @map f s@ is the set obtained by applying @f@ to each element of @s@.
361 -- It's worth noting that the size of the result may be smaller if,
362 -- for some @(x,y)@, @x \/= y && f x == f y@
364 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
365 map f = fromList . List.map f . toList
369 -- @mapMonotonic f s == 'map' f s@, but works only when @f@ is monotonic.
370 -- /The precondition is not checked./
371 -- Semi-formally, we have:
373 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
374 -- > ==> mapMonotonic f s == map f s
375 -- > where ls = toList s
377 mapMonotonic :: (a->b) -> Set a -> Set b
378 mapMonotonic f Tip = Tip
379 mapMonotonic f (Bin sz x l r) =
380 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
383 {--------------------------------------------------------------------
385 --------------------------------------------------------------------}
386 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
387 fold :: (a -> b -> b) -> b -> Set a -> b
391 -- | /O(n)/. Post-order fold.
392 foldr :: (a -> b -> b) -> b -> Set a -> b
394 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
396 {--------------------------------------------------------------------
398 --------------------------------------------------------------------}
399 -- | /O(n)/. The elements of a set.
400 elems :: Set a -> [a]
404 {--------------------------------------------------------------------
406 --------------------------------------------------------------------}
407 -- | /O(n)/. Convert the set to an ascending list of elements.
408 toList :: Set a -> [a]
412 -- | /O(n)/. Convert the set to an ascending list of elements.
413 toAscList :: Set a -> [a]
418 -- | /O(n*log n)/. Create a set from a list of elements.
419 fromList :: Ord a => [a] -> Set a
421 = foldlStrict ins empty xs
425 {--------------------------------------------------------------------
426 Building trees from ascending/descending lists can be done in linear time.
428 Note that if [xs] is ascending that:
429 fromAscList xs == fromList xs
430 --------------------------------------------------------------------}
431 -- | /O(n)/. Build a set from an ascending list in linear time.
432 -- /The precondition (input list is ascending) is not checked./
433 fromAscList :: Eq a => [a] -> Set a
435 = fromDistinctAscList (combineEq xs)
437 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
442 (x:xx) -> combineEq' x xx
444 combineEq' z [] = [z]
446 | z==x = combineEq' z xs
447 | otherwise = z:combineEq' x xs
450 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
451 -- /The precondition (input list is strictly ascending) is not checked./
452 fromDistinctAscList :: [a] -> Set a
453 fromDistinctAscList xs
454 = build const (length xs) xs
456 -- 1) use continutations so that we use heap space instead of stack space.
457 -- 2) special case for n==5 to build bushier trees.
458 build c 0 xs = c Tip xs
459 build c 5 xs = case xs of
461 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
462 build c n xs = seq nr $ build (buildR nr c) nl xs
467 buildR n c l (x:ys) = build (buildB l x c) n ys
468 buildB l x c r zs = c (bin x l r) zs
470 {--------------------------------------------------------------------
471 Eq converts the set to a list. In a lazy setting, this
472 actually seems one of the faster methods to compare two trees
473 and it is certainly the simplest :-)
474 --------------------------------------------------------------------}
475 instance Eq a => Eq (Set a) where
476 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
478 {--------------------------------------------------------------------
480 --------------------------------------------------------------------}
482 instance Ord a => Ord (Set a) where
483 compare s1 s2 = compare (toAscList s1) (toAscList s2)
485 {--------------------------------------------------------------------
487 --------------------------------------------------------------------}
489 instance Ord a => Monoid (Set a) where
494 {--------------------------------------------------------------------
496 --------------------------------------------------------------------}
497 instance Show a => Show (Set a) where
498 showsPrec d s = showSet (toAscList s)
500 showSet :: (Show a) => [a] -> ShowS
504 = showChar '{' . shows x . showTail xs
506 showTail [] = showChar '}'
507 showTail (x:xs) = showChar ',' . shows x . showTail xs
510 {--------------------------------------------------------------------
511 Utility functions that return sub-ranges of the original
512 tree. Some functions take a comparison function as argument to
513 allow comparisons against infinite values. A function [cmplo x]
514 should be read as [compare lo x].
516 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
517 and [cmphi x == GT] for the value [x] of the root.
518 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
519 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
521 [split k t] Returns two trees [l] and [r] where all values
522 in [l] are <[k] and all keys in [r] are >[k].
523 [splitMember k t] Just like [split] but also returns whether [k]
524 was found in the tree.
525 --------------------------------------------------------------------}
527 {--------------------------------------------------------------------
528 [trim lo hi t] trims away all subtrees that surely contain no
529 values between the range [lo] to [hi]. The returned tree is either
530 empty or the key of the root is between @lo@ and @hi@.
531 --------------------------------------------------------------------}
532 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
533 trim cmplo cmphi Tip = Tip
534 trim cmplo cmphi t@(Bin sx x l r)
536 LT -> case cmphi x of
538 le -> trim cmplo cmphi l
539 ge -> trim cmplo cmphi r
541 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
542 trimMemberLo lo cmphi Tip = (False,Tip)
543 trimMemberLo lo cmphi t@(Bin sx x l r)
544 = case compare lo x of
545 LT -> case cmphi x of
546 GT -> (member lo t, t)
547 le -> trimMemberLo lo cmphi l
548 GT -> trimMemberLo lo cmphi r
549 EQ -> (True,trim (compare lo) cmphi r)
552 {--------------------------------------------------------------------
553 [filterGt x t] filter all values >[x] from tree [t]
554 [filterLt x t] filter all values <[x] from tree [t]
555 --------------------------------------------------------------------}
556 filterGt :: (a -> Ordering) -> Set a -> Set a
557 filterGt cmp Tip = Tip
558 filterGt cmp (Bin sx x l r)
560 LT -> join x (filterGt cmp l) r
564 filterLt :: (a -> Ordering) -> Set a -> Set a
565 filterLt cmp Tip = Tip
566 filterLt cmp (Bin sx x l r)
569 GT -> join x l (filterLt cmp r)
573 {--------------------------------------------------------------------
575 --------------------------------------------------------------------}
576 -- | /O(log n)/. The expression (@split x set@) is a pair @(set1,set2)@
577 -- where all elements in @set1@ are lower than @x@ and all elements in
578 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
579 split :: Ord a => a -> Set a -> (Set a,Set a)
580 split x Tip = (Tip,Tip)
581 split x (Bin sy y l r)
582 = case compare x y of
583 LT -> let (lt,gt) = split x l in (lt,join y gt r)
584 GT -> let (lt,gt) = split x r in (join y l lt,gt)
587 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
588 -- element was found in the original set.
589 splitMember :: Ord a => a -> Set a -> (Bool,Set a,Set a)
590 splitMember x Tip = (False,Tip,Tip)
591 splitMember x (Bin sy y l r)
592 = case compare x y of
593 LT -> let (found,lt,gt) = splitMember x l in (found,lt,join y gt r)
594 GT -> let (found,lt,gt) = splitMember x r in (found,join y l lt,gt)
597 {--------------------------------------------------------------------
598 Utility functions that maintain the balance properties of the tree.
599 All constructors assume that all values in [l] < [x] and all values
600 in [r] > [x], and that [l] and [r] are valid trees.
602 In order of sophistication:
603 [Bin sz x l r] The type constructor.
604 [bin x l r] Maintains the correct size, assumes that both [l]
605 and [r] are balanced with respect to each other.
606 [balance x l r] Restores the balance and size.
607 Assumes that the original tree was balanced and
608 that [l] or [r] has changed by at most one element.
609 [join x l r] Restores balance and size.
611 Furthermore, we can construct a new tree from two trees. Both operations
612 assume that all values in [l] < all values in [r] and that [l] and [r]
614 [glue l r] Glues [l] and [r] together. Assumes that [l] and
615 [r] are already balanced with respect to each other.
616 [merge l r] Merges two trees and restores balance.
618 Note: in contrast to Adam's paper, we use (<=) comparisons instead
619 of (<) comparisons in [join], [merge] and [balance].
620 Quickcheck (on [difference]) showed that this was necessary in order
621 to maintain the invariants. It is quite unsatisfactory that I haven't
622 been able to find out why this is actually the case! Fortunately, it
623 doesn't hurt to be a bit more conservative.
624 --------------------------------------------------------------------}
626 {--------------------------------------------------------------------
628 --------------------------------------------------------------------}
629 join :: a -> Set a -> Set a -> Set a
630 join x Tip r = insertMin x r
631 join x l Tip = insertMax x l
632 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
633 | delta*sizeL <= sizeR = balance z (join x l lz) rz
634 | delta*sizeR <= sizeL = balance y ly (join x ry r)
635 | otherwise = bin x l r
638 -- insertMin and insertMax don't perform potentially expensive comparisons.
639 insertMax,insertMin :: a -> Set a -> Set a
644 -> balance y l (insertMax x r)
650 -> balance y (insertMin x l) r
652 {--------------------------------------------------------------------
653 [merge l r]: merges two trees.
654 --------------------------------------------------------------------}
655 merge :: Set a -> Set a -> Set a
658 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
659 | delta*sizeL <= sizeR = balance y (merge l ly) ry
660 | delta*sizeR <= sizeL = balance x lx (merge rx r)
661 | otherwise = glue l r
663 {--------------------------------------------------------------------
664 [glue l r]: glues two trees together.
665 Assumes that [l] and [r] are already balanced with respect to each other.
666 --------------------------------------------------------------------}
667 glue :: Set a -> Set a -> Set a
671 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
672 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
675 -- | /O(log n)/. Delete and find the minimal element.
677 -- > deleteFindMin set = (findMin set, deleteMin set)
679 deleteFindMin :: Set a -> (a,Set a)
682 Bin _ x Tip r -> (x,r)
683 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
684 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
686 -- | /O(log n)/. Delete and find the maximal element.
688 -- > deleteFindMax set = (findMax set, deleteMax set)
689 deleteFindMax :: Set a -> (a,Set a)
692 Bin _ x l Tip -> (x,l)
693 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
694 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
697 {--------------------------------------------------------------------
698 [balance x l r] balances two trees with value x.
699 The sizes of the trees should balance after decreasing the
700 size of one of them. (a rotation).
702 [delta] is the maximal relative difference between the sizes of
703 two trees, it corresponds with the [w] in Adams' paper,
704 or equivalently, [1/delta] corresponds with the $\alpha$
705 in Nievergelt's paper. Adams shows that [delta] should
706 be larger than 3.745 in order to garantee that the
707 rotations can always restore balance.
709 [ratio] is the ratio between an outer and inner sibling of the
710 heavier subtree in an unbalanced setting. It determines
711 whether a double or single rotation should be performed
712 to restore balance. It is correspondes with the inverse
713 of $\alpha$ in Adam's article.
716 - [delta] should be larger than 4.646 with a [ratio] of 2.
717 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
719 - A lower [delta] leads to a more 'perfectly' balanced tree.
720 - A higher [delta] performs less rebalancing.
722 - Balancing is automatic for random data and a balancing
723 scheme is only necessary to avoid pathological worst cases.
724 Almost any choice will do in practice
726 - Allthough it seems that a rather large [delta] may perform better
727 than smaller one, measurements have shown that the smallest [delta]
728 of 4 is actually the fastest on a wide range of operations. It
729 especially improves performance on worst-case scenarios like
730 a sequence of ordered insertions.
732 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
733 to decide whether a single or double rotation is needed. Allthough
734 he actually proves that this ratio is needed to maintain the
735 invariants, his implementation uses a (invalid) ratio of 1.
736 He is aware of the problem though since he has put a comment in his
737 original source code that he doesn't care about generating a
738 slightly inbalanced tree since it doesn't seem to matter in practice.
739 However (since we use quickcheck :-) we will stick to strictly balanced
741 --------------------------------------------------------------------}
746 balance :: a -> Set a -> Set a -> Set a
748 | sizeL + sizeR <= 1 = Bin sizeX x l r
749 | sizeR >= delta*sizeL = rotateL x l r
750 | sizeL >= delta*sizeR = rotateR x l r
751 | otherwise = Bin sizeX x l r
755 sizeX = sizeL + sizeR + 1
758 rotateL x l r@(Bin _ _ ly ry)
759 | size ly < ratio*size ry = singleL x l r
760 | otherwise = doubleL x l r
762 rotateR x l@(Bin _ _ ly ry) r
763 | size ry < ratio*size ly = singleR x l r
764 | otherwise = doubleR x l r
767 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
768 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
770 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
771 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
774 {--------------------------------------------------------------------
775 The bin constructor maintains the size of the tree
776 --------------------------------------------------------------------}
777 bin :: a -> Set a -> Set a -> Set a
779 = Bin (size l + size r + 1) x l r
782 {--------------------------------------------------------------------
784 --------------------------------------------------------------------}
788 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
791 {--------------------------------------------------------------------
793 --------------------------------------------------------------------}
794 -- | /O(n)/. Show the tree that implements the set. The tree is shown
795 -- in a compressed, hanging format.
796 showTree :: Show a => Set a -> String
798 = showTreeWith True False s
801 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
802 the tree that implements the set. If @hang@ is
803 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
804 @wide@ is true, an extra wide version is shown.
806 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
813 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
824 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
836 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
837 showTreeWith hang wide t
838 | hang = (showsTreeHang wide [] t) ""
839 | otherwise = (showsTree wide [] [] t) ""
841 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
842 showsTree wide lbars rbars t
844 Tip -> showsBars lbars . showString "|\n"
846 -> showsBars lbars . shows x . showString "\n"
848 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
849 showWide wide rbars .
850 showsBars lbars . shows x . showString "\n" .
851 showWide wide lbars .
852 showsTree wide (withEmpty lbars) (withBar lbars) l
854 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
855 showsTreeHang wide bars t
857 Tip -> showsBars bars . showString "|\n"
859 -> showsBars bars . shows x . showString "\n"
861 -> showsBars bars . shows x . showString "\n" .
863 showsTreeHang wide (withBar bars) l .
865 showsTreeHang wide (withEmpty bars) r
869 | wide = showString (concat (reverse bars)) . showString "|\n"
872 showsBars :: [String] -> ShowS
876 _ -> showString (concat (reverse (tail bars))) . showString node
879 withBar bars = "| ":bars
880 withEmpty bars = " ":bars
882 {--------------------------------------------------------------------
884 --------------------------------------------------------------------}
885 -- | /O(n)/. Test if the internal set structure is valid.
886 valid :: Ord a => Set a -> Bool
888 = balanced t && ordered t && validsize t
891 = bounded (const True) (const True) t
896 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
898 balanced :: Set a -> Bool
902 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
903 balanced l && balanced r
907 = (realsize t == Just (size t))
912 Bin sz x l r -> case (realsize l,realsize r) of
913 (Just n,Just m) | n+m+1 == sz -> Just sz
917 {--------------------------------------------------------------------
919 --------------------------------------------------------------------}
920 testTree :: [Int] -> Set Int
921 testTree xs = fromList xs
922 test1 = testTree [1..20]
923 test2 = testTree [30,29..10]
924 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
926 {--------------------------------------------------------------------
928 --------------------------------------------------------------------}
933 { configMaxTest = 500
934 , configMaxFail = 5000
935 , configSize = \n -> (div n 2 + 3)
936 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
940 {--------------------------------------------------------------------
941 Arbitrary, reasonably balanced trees
942 --------------------------------------------------------------------}
943 instance (Enum a) => Arbitrary (Set a) where
944 arbitrary = sized (arbtree 0 maxkey)
947 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
949 | n <= 0 = return Tip
950 | lo >= hi = return Tip
951 | otherwise = do{ i <- choose (lo,hi)
953 ; let (ml,mr) | m==(1::Int)= (1,2)
957 ; l <- arbtree lo (i-1) (n `div` ml)
958 ; r <- arbtree (i+1) hi (n `div` mr)
959 ; return (bin (toEnum i) l r)
963 {--------------------------------------------------------------------
965 --------------------------------------------------------------------}
966 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
968 = forAll arbitrary $ \t ->
969 -- classify (balanced t) "balanced" $
970 classify (size t == 0) "empty" $
971 classify (size t > 0 && size t <= 10) "small" $
972 classify (size t > 10 && size t <= 64) "medium" $
973 classify (size t > 64) "large" $
976 forValidIntTree :: Testable a => (Set Int -> a) -> Property
980 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
986 = forValidUnitTree $ \t -> valid t
988 {--------------------------------------------------------------------
989 Single, Insert, Delete
990 --------------------------------------------------------------------}
991 prop_Single :: Int -> Bool
993 = (insert x empty == singleton x)
995 prop_InsertValid :: Int -> Property
997 = forValidUnitTree $ \t -> valid (insert k t)
999 prop_InsertDelete :: Int -> Set Int -> Property
1000 prop_InsertDelete k t
1001 = not (member k t) ==> delete k (insert k t) == t
1003 prop_DeleteValid :: Int -> Property
1005 = forValidUnitTree $ \t ->
1006 valid (delete k (insert k t))
1008 {--------------------------------------------------------------------
1010 --------------------------------------------------------------------}
1011 prop_Join :: Int -> Property
1013 = forValidUnitTree $ \t ->
1014 let (l,r) = split x t
1015 in valid (join x l r)
1017 prop_Merge :: Int -> Property
1019 = forValidUnitTree $ \t ->
1020 let (l,r) = split x t
1021 in valid (merge l r)
1024 {--------------------------------------------------------------------
1026 --------------------------------------------------------------------}
1027 prop_UnionValid :: Property
1029 = forValidUnitTree $ \t1 ->
1030 forValidUnitTree $ \t2 ->
1033 prop_UnionInsert :: Int -> Set Int -> Bool
1034 prop_UnionInsert x t
1035 = union t (singleton x) == insert x t
1037 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1038 prop_UnionAssoc t1 t2 t3
1039 = union t1 (union t2 t3) == union (union t1 t2) t3
1041 prop_UnionComm :: Set Int -> Set Int -> Bool
1042 prop_UnionComm t1 t2
1043 = (union t1 t2 == union t2 t1)
1047 = forValidUnitTree $ \t1 ->
1048 forValidUnitTree $ \t2 ->
1049 valid (difference t1 t2)
1051 prop_Diff :: [Int] -> [Int] -> Bool
1053 = toAscList (difference (fromList xs) (fromList ys))
1054 == List.sort ((List.\\) (nub xs) (nub ys))
1057 = forValidUnitTree $ \t1 ->
1058 forValidUnitTree $ \t2 ->
1059 valid (intersection t1 t2)
1061 prop_Int :: [Int] -> [Int] -> Bool
1063 = toAscList (intersection (fromList xs) (fromList ys))
1064 == List.sort (nub ((List.intersect) (xs) (ys)))
1066 {--------------------------------------------------------------------
1068 --------------------------------------------------------------------}
1070 = forAll (choose (5,100)) $ \n ->
1071 let xs = [0..n::Int]
1072 in fromAscList xs == fromList xs
1074 prop_List :: [Int] -> Bool
1076 = (sort (nub xs) == toList (fromList xs))
1079 {--------------------------------------------------------------------
1080 Old Data.Set compatibility interface
1081 --------------------------------------------------------------------}
1083 {-# DEPRECATED emptySet "Use empty instead" #-}
1087 {-# DEPRECATED mkSet "Equivalent to 'foldl insert empty'." #-}
1088 mkSet :: Ord a => [a] -> Set a
1089 mkSet = List.foldl' (flip insert) empty
1091 {-# DEPRECATED setToList "Use instead." #-}
1092 setToList :: Set a -> [a]
1095 {-# DEPRECATED unitSet "Use singleton instead." #-}
1096 unitSet :: a -> Set a
1099 {-# DEPRECATED elementOf "Use member instead." #-}
1100 elementOf :: Ord a => a -> Set a -> Bool
1103 {-# DEPRECATED isEmptySet "Use null instead." #-}
1104 isEmptySet :: Set a -> Bool
1107 {-# DEPRECATED cardinality "Use size instead." #-}
1108 cardinality :: Set a -> Int
1111 {-# DEPRECATED unionManySets "Use unions instead." #-}
1112 unionManySets :: Ord a => [Set a] -> Set a
1113 unionManySets = unions
1115 {-# DEPRECATED minusSet "Use difference instead." #-}
1116 minusSet :: Ord a => Set a -> Set a -> Set a
1117 minusSet = difference
1119 {-# DEPRECATED mapSet "Use map instead." #-}
1120 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1123 {-# DEPRECATED intersect "Use intersection instead." #-}
1124 intersect :: Ord a => Set a -> Set a -> Set a
1125 intersect = intersection
1127 {-# DEPRECATED addToSet "Use insert instead." #-}
1128 addToSet :: Ord a => Set a -> a -> Set a
1129 addToSet = flip insert
1131 {-# DEPRECATED delFromSet "Use delete instead." #-}
1132 delFromSet :: Ord a => Set a -> a -> Set a
1133 delFromSet = flip delete