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 -- Since many function names (but not the type name) clash with
13 -- "Prelude" names, this module is usually imported @qualified@, e.g.
15 -- > import Data.Set (Set)
16 -- > import qualified Data.Set as Set
18 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
19 -- trees of /bounded balance/) as described by:
21 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
22 -- Journal of Functional Programming 3(4):553-562, October 1993,
23 -- <http://www.swiss.ai.mit.edu/~adams/BB>.
25 -- * J. Nievergelt and E.M. Reingold,
26 -- \"/Binary search trees of bounded balance/\",
27 -- SIAM journal of computing 2(1), March 1973.
29 -- Note that the implementation is /left-biased/ -- the elements of a
30 -- first argument are always preferred to the second, for example in
31 -- 'union' or 'insert'. Of course, left-biasing can only be observed
32 -- when equality is an equivalence relation instead of structural
34 -----------------------------------------------------------------------------
38 Set -- instance Eq,Ord,Show,Read,Data,Typeable
103 import Prelude hiding (filter,foldr,null,map)
104 import qualified Data.List as List
105 import Data.Monoid (Monoid(..))
107 import Data.Foldable (Foldable(foldMap))
112 import List (nub,sort)
113 import qualified List
116 #if __GLASGOW_HASKELL__
118 import Data.Generics.Basics
119 import Data.Generics.Instances
122 {--------------------------------------------------------------------
124 --------------------------------------------------------------------}
127 -- | /O(n+m)/. See 'difference'.
128 (\\) :: Ord a => Set a -> Set a -> Set a
129 m1 \\ m2 = difference m1 m2
131 {--------------------------------------------------------------------
132 Sets are size balanced trees
133 --------------------------------------------------------------------}
134 -- | A set of values @a@.
136 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
140 instance Ord a => Monoid (Set a) where
145 instance Foldable Set where
146 foldMap f Tip = mempty
147 foldMap f (Bin _s k l r) = foldMap f l `mappend` f k `mappend` foldMap f r
149 #if __GLASGOW_HASKELL__
151 {--------------------------------------------------------------------
153 --------------------------------------------------------------------}
155 -- This instance preserves data abstraction at the cost of inefficiency.
156 -- We omit reflection services for the sake of data abstraction.
158 instance (Data a, Ord a) => Data (Set a) where
159 gfoldl f z set = z fromList `f` (toList set)
160 toConstr _ = error "toConstr"
161 gunfold _ _ = error "gunfold"
162 dataTypeOf _ = mkNorepType "Data.Set.Set"
163 dataCast1 f = gcast1 f
167 {--------------------------------------------------------------------
169 --------------------------------------------------------------------}
170 -- | /O(1)/. Is this the empty set?
171 null :: Set a -> Bool
175 Bin sz x l r -> False
177 -- | /O(1)/. The number of elements in the set.
184 -- | /O(log n)/. Is the element in the set?
185 member :: Ord a => a -> Set a -> Bool
190 -> case compare x y of
195 -- | /O(log n)/. Is the element not in the set?
196 notMember :: Ord a => a -> Set a -> Bool
197 notMember x t = not $ member x t
199 {--------------------------------------------------------------------
201 --------------------------------------------------------------------}
202 -- | /O(1)/. The empty set.
207 -- | /O(1)/. Create a singleton set.
208 singleton :: a -> Set a
212 {--------------------------------------------------------------------
214 --------------------------------------------------------------------}
215 -- | /O(log n)/. Insert an element in a set.
216 -- If the set already contains an element equal to the given value,
217 -- it is replaced with the new value.
218 insert :: Ord a => a -> Set a -> Set a
223 -> case compare x y of
224 LT -> balance y (insert x l) r
225 GT -> balance y l (insert x r)
229 -- | /O(log n)/. Delete an element from a set.
230 delete :: Ord a => a -> Set a -> Set a
235 -> case compare x y of
236 LT -> balance y (delete x l) r
237 GT -> balance y l (delete x r)
240 {--------------------------------------------------------------------
242 --------------------------------------------------------------------}
243 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
244 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
245 isProperSubsetOf s1 s2
246 = (size s1 < size s2) && (isSubsetOf s1 s2)
249 -- | /O(n+m)/. Is this a subset?
250 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
251 isSubsetOf :: Ord a => Set a -> Set a -> Bool
253 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
255 isSubsetOfX Tip t = True
256 isSubsetOfX t Tip = False
257 isSubsetOfX (Bin _ x l r) t
258 = found && isSubsetOfX l lt && isSubsetOfX r gt
260 (lt,found,gt) = splitMember x t
263 {--------------------------------------------------------------------
265 --------------------------------------------------------------------}
266 -- | /O(log n)/. The minimal element of a set.
267 findMin :: Set a -> a
268 findMin (Bin _ x Tip r) = x
269 findMin (Bin _ x l r) = findMin l
270 findMin Tip = error "Set.findMin: empty set has no minimal element"
272 -- | /O(log n)/. The maximal element of a set.
273 findMax :: Set a -> a
274 findMax (Bin _ x l Tip) = x
275 findMax (Bin _ x l r) = findMax r
276 findMax Tip = error "Set.findMax: empty set has no maximal element"
278 -- | /O(log n)/. Delete the minimal element.
279 deleteMin :: Set a -> Set a
280 deleteMin (Bin _ x Tip r) = r
281 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
284 -- | /O(log n)/. Delete the maximal element.
285 deleteMax :: Set a -> Set a
286 deleteMax (Bin _ x l Tip) = l
287 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
291 {--------------------------------------------------------------------
293 --------------------------------------------------------------------}
294 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
295 unions :: Ord a => [Set a] -> Set a
297 = foldlStrict union empty ts
300 -- | /O(n+m)/. The union of two sets, preferring the first set when
301 -- equal elements are encountered.
302 -- The implementation uses the efficient /hedge-union/ algorithm.
303 -- Hedge-union is more efficient on (bigset `union` smallset).
304 union :: Ord a => Set a -> Set a -> Set a
307 union t1 t2 = hedgeUnion (const LT) (const GT) t1 t2
309 hedgeUnion cmplo cmphi t1 Tip
311 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
312 = join x (filterGt cmplo l) (filterLt cmphi r)
313 hedgeUnion cmplo cmphi (Bin _ x l r) t2
314 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
315 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
319 {--------------------------------------------------------------------
321 --------------------------------------------------------------------}
322 -- | /O(n+m)/. Difference of two sets.
323 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
324 difference :: Ord a => Set a -> Set a -> Set a
325 difference Tip t2 = Tip
326 difference t1 Tip = t1
327 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
329 hedgeDiff cmplo cmphi Tip t
331 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
332 = join x (filterGt cmplo l) (filterLt cmphi r)
333 hedgeDiff cmplo cmphi t (Bin _ x l r)
334 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
335 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
339 {--------------------------------------------------------------------
341 --------------------------------------------------------------------}
342 -- | /O(n+m)/. The intersection of two sets.
343 -- Elements of the result come from the first set.
344 intersection :: Ord a => Set a -> Set a -> Set a
345 intersection Tip t = Tip
346 intersection t Tip = Tip
347 intersection t1@(Bin s1 x1 l1 r1) t2@(Bin s2 x2 l2 r2) =
349 let (lt,found,gt) = splitLookup x2 t1
350 tl = intersection lt l2
351 tr = intersection gt r2
353 Just x -> join x tl tr
354 Nothing -> merge tl tr
355 else let (lt,found,gt) = splitMember x1 t2
356 tl = intersection l1 lt
357 tr = intersection r1 gt
358 in if found then join x1 tl tr
361 {--------------------------------------------------------------------
363 --------------------------------------------------------------------}
364 -- | /O(n)/. Filter all elements that satisfy the predicate.
365 filter :: Ord a => (a -> Bool) -> Set a -> Set a
367 filter p (Bin _ x l r)
368 | p x = join x (filter p l) (filter p r)
369 | otherwise = merge (filter p l) (filter p r)
371 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
372 -- the predicate and one with all elements that don't satisfy the predicate.
374 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
375 partition p Tip = (Tip,Tip)
376 partition p (Bin _ x l r)
377 | p x = (join x l1 r1,merge l2 r2)
378 | otherwise = (merge l1 r1,join x l2 r2)
380 (l1,l2) = partition p l
381 (r1,r2) = partition p r
383 {----------------------------------------------------------------------
385 ----------------------------------------------------------------------}
388 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
390 -- It's worth noting that the size of the result may be smaller if,
391 -- for some @(x,y)@, @x \/= y && f x == f y@
393 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
394 map f = fromList . List.map f . toList
398 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
399 -- /The precondition is not checked./
400 -- Semi-formally, we have:
402 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
403 -- > ==> mapMonotonic f s == map f s
404 -- > where ls = toList s
406 mapMonotonic :: (a->b) -> Set a -> Set b
407 mapMonotonic f Tip = Tip
408 mapMonotonic f (Bin sz x l r) =
409 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
412 {--------------------------------------------------------------------
414 --------------------------------------------------------------------}
415 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
416 fold :: (a -> b -> b) -> b -> Set a -> b
420 -- | /O(n)/. Post-order fold.
421 foldr :: (a -> b -> b) -> b -> Set a -> b
423 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
425 {--------------------------------------------------------------------
427 --------------------------------------------------------------------}
428 -- | /O(n)/. The elements of a set.
429 elems :: Set a -> [a]
433 {--------------------------------------------------------------------
435 --------------------------------------------------------------------}
436 -- | /O(n)/. Convert the set to a list of elements.
437 toList :: Set a -> [a]
441 -- | /O(n)/. Convert the set to an ascending list of elements.
442 toAscList :: Set a -> [a]
447 -- | /O(n*log n)/. Create a set from a list of elements.
448 fromList :: Ord a => [a] -> Set a
450 = foldlStrict ins empty xs
454 {--------------------------------------------------------------------
455 Building trees from ascending/descending lists can be done in linear time.
457 Note that if [xs] is ascending that:
458 fromAscList xs == fromList xs
459 --------------------------------------------------------------------}
460 -- | /O(n)/. Build a set from an ascending list in linear time.
461 -- /The precondition (input list is ascending) is not checked./
462 fromAscList :: Eq a => [a] -> Set a
464 = fromDistinctAscList (combineEq xs)
466 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
471 (x:xx) -> combineEq' x xx
473 combineEq' z [] = [z]
475 | z==x = combineEq' z xs
476 | otherwise = z:combineEq' x xs
479 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
480 -- /The precondition (input list is strictly ascending) is not checked./
481 fromDistinctAscList :: [a] -> Set a
482 fromDistinctAscList xs
483 = build const (length xs) xs
485 -- 1) use continutations so that we use heap space instead of stack space.
486 -- 2) special case for n==5 to build bushier trees.
487 build c 0 xs = c Tip xs
488 build c 5 xs = case xs of
490 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
491 build c n xs = seq nr $ build (buildR nr c) nl xs
496 buildR n c l (x:ys) = build (buildB l x c) n ys
497 buildB l x c r zs = c (bin x l r) zs
499 {--------------------------------------------------------------------
500 Eq converts the set to a list. In a lazy setting, this
501 actually seems one of the faster methods to compare two trees
502 and it is certainly the simplest :-)
503 --------------------------------------------------------------------}
504 instance Eq a => Eq (Set a) where
505 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
507 {--------------------------------------------------------------------
509 --------------------------------------------------------------------}
511 instance Ord a => Ord (Set a) where
512 compare s1 s2 = compare (toAscList s1) (toAscList s2)
514 {--------------------------------------------------------------------
516 --------------------------------------------------------------------}
517 instance Show a => Show (Set a) where
518 showsPrec p xs = showParen (p > 10) $
519 showString "fromList " . shows (toList xs)
521 showSet :: (Show a) => [a] -> ShowS
525 = showChar '{' . shows x . showTail xs
527 showTail [] = showChar '}'
528 showTail (x:xs) = showChar ',' . shows x . showTail xs
530 {--------------------------------------------------------------------
532 --------------------------------------------------------------------}
533 instance (Read a, Ord a) => Read (Set a) where
534 #ifdef __GLASGOW_HASKELL__
535 readPrec = parens $ prec 10 $ do
536 Ident "fromList" <- lexP
540 readListPrec = readListPrecDefault
542 readsPrec p = readParen (p > 10) $ \ r -> do
543 ("fromList",s) <- lex r
545 return (fromList xs,t)
548 {--------------------------------------------------------------------
550 --------------------------------------------------------------------}
552 #include "Typeable.h"
553 INSTANCE_TYPEABLE1(Set,setTc,"Set")
555 {--------------------------------------------------------------------
556 Utility functions that return sub-ranges of the original
557 tree. Some functions take a comparison function as argument to
558 allow comparisons against infinite values. A function [cmplo x]
559 should be read as [compare lo x].
561 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
562 and [cmphi x == GT] for the value [x] of the root.
563 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
564 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
566 [split k t] Returns two trees [l] and [r] where all values
567 in [l] are <[k] and all keys in [r] are >[k].
568 [splitMember k t] Just like [split] but also returns whether [k]
569 was found in the tree.
570 --------------------------------------------------------------------}
572 {--------------------------------------------------------------------
573 [trim lo hi t] trims away all subtrees that surely contain no
574 values between the range [lo] to [hi]. The returned tree is either
575 empty or the key of the root is between @lo@ and @hi@.
576 --------------------------------------------------------------------}
577 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
578 trim cmplo cmphi Tip = Tip
579 trim cmplo cmphi t@(Bin sx x l r)
581 LT -> case cmphi x of
583 le -> trim cmplo cmphi l
584 ge -> trim cmplo cmphi r
586 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
587 trimMemberLo lo cmphi Tip = (False,Tip)
588 trimMemberLo lo cmphi t@(Bin sx x l r)
589 = case compare lo x of
590 LT -> case cmphi x of
591 GT -> (member lo t, t)
592 le -> trimMemberLo lo cmphi l
593 GT -> trimMemberLo lo cmphi r
594 EQ -> (True,trim (compare lo) cmphi r)
597 {--------------------------------------------------------------------
598 [filterGt x t] filter all values >[x] from tree [t]
599 [filterLt x t] filter all values <[x] from tree [t]
600 --------------------------------------------------------------------}
601 filterGt :: (a -> Ordering) -> Set a -> Set a
602 filterGt cmp Tip = Tip
603 filterGt cmp (Bin sx x l r)
605 LT -> join x (filterGt cmp l) r
609 filterLt :: (a -> Ordering) -> Set a -> Set a
610 filterLt cmp Tip = Tip
611 filterLt cmp (Bin sx x l r)
614 GT -> join x l (filterLt cmp r)
618 {--------------------------------------------------------------------
620 --------------------------------------------------------------------}
621 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
622 -- where all elements in @set1@ are lower than @x@ and all elements in
623 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
624 split :: Ord a => a -> Set a -> (Set a,Set a)
625 split x Tip = (Tip,Tip)
626 split x (Bin sy y l r)
627 = case compare x y of
628 LT -> let (lt,gt) = split x l in (lt,join y gt r)
629 GT -> let (lt,gt) = split x r in (join y l lt,gt)
632 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
633 -- element was found in the original set.
634 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
635 splitMember x t = let (l,m,r) = splitLookup x t in
636 (l,maybe False (const True) m,r)
638 -- | /O(log n)/. Performs a 'split' but also returns the pivot
639 -- element that was found in the original set.
640 splitLookup :: Ord a => a -> Set a -> (Set a,Maybe a,Set a)
641 splitLookup x Tip = (Tip,Nothing,Tip)
642 splitLookup x (Bin sy y l r)
643 = case compare x y of
644 LT -> let (lt,found,gt) = splitLookup x l in (lt,found,join y gt r)
645 GT -> let (lt,found,gt) = splitLookup x r in (join y l lt,found,gt)
648 {--------------------------------------------------------------------
649 Utility functions that maintain the balance properties of the tree.
650 All constructors assume that all values in [l] < [x] and all values
651 in [r] > [x], and that [l] and [r] are valid trees.
653 In order of sophistication:
654 [Bin sz x l r] The type constructor.
655 [bin x l r] Maintains the correct size, assumes that both [l]
656 and [r] are balanced with respect to each other.
657 [balance x l r] Restores the balance and size.
658 Assumes that the original tree was balanced and
659 that [l] or [r] has changed by at most one element.
660 [join x l r] Restores balance and size.
662 Furthermore, we can construct a new tree from two trees. Both operations
663 assume that all values in [l] < all values in [r] and that [l] and [r]
665 [glue l r] Glues [l] and [r] together. Assumes that [l] and
666 [r] are already balanced with respect to each other.
667 [merge l r] Merges two trees and restores balance.
669 Note: in contrast to Adam's paper, we use (<=) comparisons instead
670 of (<) comparisons in [join], [merge] and [balance].
671 Quickcheck (on [difference]) showed that this was necessary in order
672 to maintain the invariants. It is quite unsatisfactory that I haven't
673 been able to find out why this is actually the case! Fortunately, it
674 doesn't hurt to be a bit more conservative.
675 --------------------------------------------------------------------}
677 {--------------------------------------------------------------------
679 --------------------------------------------------------------------}
680 join :: a -> Set a -> Set a -> Set a
681 join x Tip r = insertMin x r
682 join x l Tip = insertMax x l
683 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
684 | delta*sizeL <= sizeR = balance z (join x l lz) rz
685 | delta*sizeR <= sizeL = balance y ly (join x ry r)
686 | otherwise = bin x l r
689 -- insertMin and insertMax don't perform potentially expensive comparisons.
690 insertMax,insertMin :: a -> Set a -> Set a
695 -> balance y l (insertMax x r)
701 -> balance y (insertMin x l) r
703 {--------------------------------------------------------------------
704 [merge l r]: merges two trees.
705 --------------------------------------------------------------------}
706 merge :: Set a -> Set a -> Set a
709 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
710 | delta*sizeL <= sizeR = balance y (merge l ly) ry
711 | delta*sizeR <= sizeL = balance x lx (merge rx r)
712 | otherwise = glue l r
714 {--------------------------------------------------------------------
715 [glue l r]: glues two trees together.
716 Assumes that [l] and [r] are already balanced with respect to each other.
717 --------------------------------------------------------------------}
718 glue :: Set a -> Set a -> Set a
722 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
723 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
726 -- | /O(log n)/. Delete and find the minimal element.
728 -- > deleteFindMin set = (findMin set, deleteMin set)
730 deleteFindMin :: Set a -> (a,Set a)
733 Bin _ x Tip r -> (x,r)
734 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
735 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
737 -- | /O(log n)/. Delete and find the maximal element.
739 -- > deleteFindMax set = (findMax set, deleteMax set)
740 deleteFindMax :: Set a -> (a,Set a)
743 Bin _ x l Tip -> (x,l)
744 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
745 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
747 -- | /O(log n)/. Retrieves the minimal key of the set, and the set stripped from that element
748 -- @fail@s (in the monad) when passed an empty set.
749 minView :: Monad m => Set a -> m (a, Set a)
750 minView Tip = fail "Set.minView: empty set"
751 minView x = return (deleteFindMin x)
753 -- | /O(log n)/. Retrieves the maximal key of the set, and the set stripped from that element
754 -- @fail@s (in the monad) when passed an empty set.
755 maxView :: Monad m => Set a -> m (a, Set a)
756 maxView Tip = fail "Set.maxView: empty set"
757 maxView x = return (deleteFindMax x)
760 {--------------------------------------------------------------------
761 [balance x l r] balances two trees with value x.
762 The sizes of the trees should balance after decreasing the
763 size of one of them. (a rotation).
765 [delta] is the maximal relative difference between the sizes of
766 two trees, it corresponds with the [w] in Adams' paper,
767 or equivalently, [1/delta] corresponds with the $\alpha$
768 in Nievergelt's paper. Adams shows that [delta] should
769 be larger than 3.745 in order to garantee that the
770 rotations can always restore balance.
772 [ratio] is the ratio between an outer and inner sibling of the
773 heavier subtree in an unbalanced setting. It determines
774 whether a double or single rotation should be performed
775 to restore balance. It is correspondes with the inverse
776 of $\alpha$ in Adam's article.
779 - [delta] should be larger than 4.646 with a [ratio] of 2.
780 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
782 - A lower [delta] leads to a more 'perfectly' balanced tree.
783 - A higher [delta] performs less rebalancing.
785 - Balancing is automatic for random data and a balancing
786 scheme is only necessary to avoid pathological worst cases.
787 Almost any choice will do in practice
789 - Allthough it seems that a rather large [delta] may perform better
790 than smaller one, measurements have shown that the smallest [delta]
791 of 4 is actually the fastest on a wide range of operations. It
792 especially improves performance on worst-case scenarios like
793 a sequence of ordered insertions.
795 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
796 to decide whether a single or double rotation is needed. Allthough
797 he actually proves that this ratio is needed to maintain the
798 invariants, his implementation uses a (invalid) ratio of 1.
799 He is aware of the problem though since he has put a comment in his
800 original source code that he doesn't care about generating a
801 slightly inbalanced tree since it doesn't seem to matter in practice.
802 However (since we use quickcheck :-) we will stick to strictly balanced
804 --------------------------------------------------------------------}
809 balance :: a -> Set a -> Set a -> Set a
811 | sizeL + sizeR <= 1 = Bin sizeX x l r
812 | sizeR >= delta*sizeL = rotateL x l r
813 | sizeL >= delta*sizeR = rotateR x l r
814 | otherwise = Bin sizeX x l r
818 sizeX = sizeL + sizeR + 1
821 rotateL x l r@(Bin _ _ ly ry)
822 | size ly < ratio*size ry = singleL x l r
823 | otherwise = doubleL x l r
825 rotateR x l@(Bin _ _ ly ry) r
826 | size ry < ratio*size ly = singleR x l r
827 | otherwise = doubleR x l r
830 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
831 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
833 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
834 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
837 {--------------------------------------------------------------------
838 The bin constructor maintains the size of the tree
839 --------------------------------------------------------------------}
840 bin :: a -> Set a -> Set a -> Set a
842 = Bin (size l + size r + 1) x l r
845 {--------------------------------------------------------------------
847 --------------------------------------------------------------------}
851 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
854 {--------------------------------------------------------------------
856 --------------------------------------------------------------------}
857 -- | /O(n)/. Show the tree that implements the set. The tree is shown
858 -- in a compressed, hanging format.
859 showTree :: Show a => Set a -> String
861 = showTreeWith True False s
864 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
865 the tree that implements the set. If @hang@ is
866 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
867 @wide@ is 'True', an extra wide version is shown.
869 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
876 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
887 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
899 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
900 showTreeWith hang wide t
901 | hang = (showsTreeHang wide [] t) ""
902 | otherwise = (showsTree wide [] [] t) ""
904 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
905 showsTree wide lbars rbars t
907 Tip -> showsBars lbars . showString "|\n"
909 -> showsBars lbars . shows x . showString "\n"
911 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
912 showWide wide rbars .
913 showsBars lbars . shows x . showString "\n" .
914 showWide wide lbars .
915 showsTree wide (withEmpty lbars) (withBar lbars) l
917 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
918 showsTreeHang wide bars t
920 Tip -> showsBars bars . showString "|\n"
922 -> showsBars bars . shows x . showString "\n"
924 -> showsBars bars . shows x . showString "\n" .
926 showsTreeHang wide (withBar bars) l .
928 showsTreeHang wide (withEmpty bars) r
932 | wide = showString (concat (reverse bars)) . showString "|\n"
935 showsBars :: [String] -> ShowS
939 _ -> showString (concat (reverse (tail bars))) . showString node
942 withBar bars = "| ":bars
943 withEmpty bars = " ":bars
945 {--------------------------------------------------------------------
947 --------------------------------------------------------------------}
948 -- | /O(n)/. Test if the internal set structure is valid.
949 valid :: Ord a => Set a -> Bool
951 = balanced t && ordered t && validsize t
954 = bounded (const True) (const True) t
959 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
961 balanced :: Set a -> Bool
965 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
966 balanced l && balanced r
970 = (realsize t == Just (size t))
975 Bin sz x l r -> case (realsize l,realsize r) of
976 (Just n,Just m) | n+m+1 == sz -> Just sz
980 {--------------------------------------------------------------------
982 --------------------------------------------------------------------}
983 testTree :: [Int] -> Set Int
984 testTree xs = fromList xs
985 test1 = testTree [1..20]
986 test2 = testTree [30,29..10]
987 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
989 {--------------------------------------------------------------------
991 --------------------------------------------------------------------}
996 { configMaxTest = 500
997 , configMaxFail = 5000
998 , configSize = \n -> (div n 2 + 3)
999 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1003 {--------------------------------------------------------------------
1004 Arbitrary, reasonably balanced trees
1005 --------------------------------------------------------------------}
1006 instance (Enum a) => Arbitrary (Set a) where
1007 arbitrary = sized (arbtree 0 maxkey)
1008 where maxkey = 10000
1010 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
1012 | n <= 0 = return Tip
1013 | lo >= hi = return Tip
1014 | otherwise = do{ i <- choose (lo,hi)
1015 ; m <- choose (1,30)
1016 ; let (ml,mr) | m==(1::Int)= (1,2)
1020 ; l <- arbtree lo (i-1) (n `div` ml)
1021 ; r <- arbtree (i+1) hi (n `div` mr)
1022 ; return (bin (toEnum i) l r)
1026 {--------------------------------------------------------------------
1028 --------------------------------------------------------------------}
1029 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1031 = forAll arbitrary $ \t ->
1032 -- classify (balanced t) "balanced" $
1033 classify (size t == 0) "empty" $
1034 classify (size t > 0 && size t <= 10) "small" $
1035 classify (size t > 10 && size t <= 64) "medium" $
1036 classify (size t > 64) "large" $
1039 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1043 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1049 = forValidUnitTree $ \t -> valid t
1051 {--------------------------------------------------------------------
1052 Single, Insert, Delete
1053 --------------------------------------------------------------------}
1054 prop_Single :: Int -> Bool
1056 = (insert x empty == singleton x)
1058 prop_InsertValid :: Int -> Property
1060 = forValidUnitTree $ \t -> valid (insert k t)
1062 prop_InsertDelete :: Int -> Set Int -> Property
1063 prop_InsertDelete k t
1064 = not (member k t) ==> delete k (insert k t) == t
1066 prop_DeleteValid :: Int -> Property
1068 = forValidUnitTree $ \t ->
1069 valid (delete k (insert k t))
1071 {--------------------------------------------------------------------
1073 --------------------------------------------------------------------}
1074 prop_Join :: Int -> Property
1076 = forValidUnitTree $ \t ->
1077 let (l,r) = split x t
1078 in valid (join x l r)
1080 prop_Merge :: Int -> Property
1082 = forValidUnitTree $ \t ->
1083 let (l,r) = split x t
1084 in valid (merge l r)
1087 {--------------------------------------------------------------------
1089 --------------------------------------------------------------------}
1090 prop_UnionValid :: Property
1092 = forValidUnitTree $ \t1 ->
1093 forValidUnitTree $ \t2 ->
1096 prop_UnionInsert :: Int -> Set Int -> Bool
1097 prop_UnionInsert x t
1098 = union t (singleton x) == insert x t
1100 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1101 prop_UnionAssoc t1 t2 t3
1102 = union t1 (union t2 t3) == union (union t1 t2) t3
1104 prop_UnionComm :: Set Int -> Set Int -> Bool
1105 prop_UnionComm t1 t2
1106 = (union t1 t2 == union t2 t1)
1110 = forValidUnitTree $ \t1 ->
1111 forValidUnitTree $ \t2 ->
1112 valid (difference t1 t2)
1114 prop_Diff :: [Int] -> [Int] -> Bool
1116 = toAscList (difference (fromList xs) (fromList ys))
1117 == List.sort ((List.\\) (nub xs) (nub ys))
1120 = forValidUnitTree $ \t1 ->
1121 forValidUnitTree $ \t2 ->
1122 valid (intersection t1 t2)
1124 prop_Int :: [Int] -> [Int] -> Bool
1126 = toAscList (intersection (fromList xs) (fromList ys))
1127 == List.sort (nub ((List.intersect) (xs) (ys)))
1129 {--------------------------------------------------------------------
1131 --------------------------------------------------------------------}
1133 = forAll (choose (5,100)) $ \n ->
1134 let xs = [0..n::Int]
1135 in fromAscList xs == fromList xs
1137 prop_List :: [Int] -> Bool
1139 = (sort (nub xs) == toList (fromList xs))