1 -----------------------------------------------------------------------------
4 -- Copyright : (c) Daan Leijen 2002
6 -- Maintainer : libraries@haskell.org
7 -- Stability : provisional
8 -- Portability : portable
10 -- An efficient implementation of sets.
12 -- This module is intended to be imported @qualified@, to avoid name
13 -- clashes with "Prelude" functions. eg.
15 -- > import Data.Set as Set
17 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
18 -- trees of /bounded balance/) as described by:
20 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
21 -- Journal of Functional Programming 3(4):553-562, October 1993,
22 -- <http://www.swiss.ai.mit.edu/~adams/BB>.
24 -- * J. Nievergelt and E.M. Reingold,
25 -- \"/Binary search trees of bounded balance/\",
26 -- SIAM journal of computing 2(1), March 1973.
28 -- Note that the implementation is /left-biased/ -- the elements of a
29 -- first argument are always preferred to the second, for example in
30 -- 'union' or 'insert'. Of course, left-biasing can only be observed
31 -- when equality is an equivalence relation instead of structural
33 -----------------------------------------------------------------------------
37 Set -- instance Eq,Ord,Show,Read,Data,Typeable
102 import Prelude hiding (filter,foldr,null,map)
103 import qualified Data.List as List
104 import Data.Monoid (Monoid(..))
106 import Data.Foldable (Foldable(foldMap))
111 import List (nub,sort)
112 import qualified List
115 #if __GLASGOW_HASKELL__
117 import Data.Generics.Basics
118 import Data.Generics.Instances
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 instance Ord a => Monoid (Set a) where
144 instance Foldable Set where
145 foldMap f Tip = mempty
146 foldMap f (Bin _s k l r) = foldMap f l `mappend` f k `mappend` foldMap f r
148 #if __GLASGOW_HASKELL__
150 {--------------------------------------------------------------------
152 --------------------------------------------------------------------}
154 -- This instance preserves data abstraction at the cost of inefficiency.
155 -- We omit reflection services for the sake of data abstraction.
157 instance (Data a, Ord a) => Data (Set a) where
158 gfoldl f z set = z fromList `f` (toList set)
159 toConstr _ = error "toConstr"
160 gunfold _ _ = error "gunfold"
161 dataTypeOf _ = mkNorepType "Data.Set.Set"
162 dataCast1 f = gcast1 f
166 {--------------------------------------------------------------------
168 --------------------------------------------------------------------}
169 -- | /O(1)/. Is this the empty set?
170 null :: Set a -> Bool
174 Bin sz x l r -> False
176 -- | /O(1)/. The number of elements in the set.
183 -- | /O(log n)/. Is the element in the set?
184 member :: Ord a => a -> Set a -> Bool
189 -> case compare x y of
194 -- | /O(log n)/. Is the element not in the set?
195 notMember :: Ord a => a -> Set a -> Bool
196 notMember x t = not $ member x t
198 {--------------------------------------------------------------------
200 --------------------------------------------------------------------}
201 -- | /O(1)/. The empty set.
206 -- | /O(1)/. Create a singleton set.
207 singleton :: a -> Set a
211 {--------------------------------------------------------------------
213 --------------------------------------------------------------------}
214 -- | /O(log n)/. Insert an element in a set.
215 -- If the set already contains an element equal to the given value,
216 -- it is replaced with the new value.
217 insert :: Ord a => a -> Set a -> Set a
222 -> case compare x y of
223 LT -> balance y (insert x l) r
224 GT -> balance y l (insert x r)
228 -- | /O(log n)/. Delete an element from a set.
229 delete :: Ord a => a -> Set a -> Set a
234 -> case compare x y of
235 LT -> balance y (delete x l) r
236 GT -> balance y l (delete x r)
239 {--------------------------------------------------------------------
241 --------------------------------------------------------------------}
242 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
243 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
244 isProperSubsetOf s1 s2
245 = (size s1 < size s2) && (isSubsetOf s1 s2)
248 -- | /O(n+m)/. Is this a subset?
249 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
250 isSubsetOf :: Ord a => Set a -> Set a -> Bool
252 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
254 isSubsetOfX Tip t = True
255 isSubsetOfX t Tip = False
256 isSubsetOfX (Bin _ x l r) t
257 = found && isSubsetOfX l lt && isSubsetOfX r gt
259 (lt,found,gt) = splitMember x t
262 {--------------------------------------------------------------------
264 --------------------------------------------------------------------}
265 -- | /O(log n)/. The minimal element of a set.
266 findMin :: Set a -> a
267 findMin (Bin _ x Tip r) = x
268 findMin (Bin _ x l r) = findMin l
269 findMin Tip = error "Set.findMin: empty set has no minimal element"
271 -- | /O(log n)/. The maximal element of a set.
272 findMax :: Set a -> a
273 findMax (Bin _ x l Tip) = x
274 findMax (Bin _ x l r) = findMax r
275 findMax Tip = error "Set.findMax: empty set has no maximal element"
277 -- | /O(log n)/. Delete the minimal element.
278 deleteMin :: Set a -> Set a
279 deleteMin (Bin _ x Tip r) = r
280 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
283 -- | /O(log n)/. Delete the maximal element.
284 deleteMax :: Set a -> Set a
285 deleteMax (Bin _ x l Tip) = l
286 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
290 {--------------------------------------------------------------------
292 --------------------------------------------------------------------}
293 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
294 unions :: Ord a => [Set a] -> Set a
296 = foldlStrict union empty ts
299 -- | /O(n+m)/. The union of two sets, preferring the first set when
300 -- equal elements are encountered.
301 -- The implementation uses the efficient /hedge-union/ algorithm.
302 -- Hedge-union is more efficient on (bigset `union` smallset).
303 union :: Ord a => Set a -> Set a -> Set a
306 union t1 t2 = hedgeUnion (const LT) (const GT) t1 t2
308 hedgeUnion cmplo cmphi t1 Tip
310 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
311 = join x (filterGt cmplo l) (filterLt cmphi r)
312 hedgeUnion cmplo cmphi (Bin _ x l r) t2
313 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
314 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
318 {--------------------------------------------------------------------
320 --------------------------------------------------------------------}
321 -- | /O(n+m)/. Difference of two sets.
322 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
323 difference :: Ord a => Set a -> Set a -> Set a
324 difference Tip t2 = Tip
325 difference t1 Tip = t1
326 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
328 hedgeDiff cmplo cmphi Tip t
330 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
331 = join x (filterGt cmplo l) (filterLt cmphi r)
332 hedgeDiff cmplo cmphi t (Bin _ x l r)
333 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
334 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
338 {--------------------------------------------------------------------
340 --------------------------------------------------------------------}
341 -- | /O(n+m)/. The intersection of two sets.
342 -- Elements of the result come from the first set.
343 intersection :: Ord a => Set a -> Set a -> Set a
344 intersection Tip t = Tip
345 intersection t Tip = Tip
346 intersection t1@(Bin s1 x1 l1 r1) t2@(Bin s2 x2 l2 r2) =
348 let (lt,found,gt) = splitLookup x2 t1
349 tl = intersection lt l2
350 tr = intersection gt r2
352 Just x -> join x tl tr
353 Nothing -> merge tl tr
354 else let (lt,found,gt) = splitMember x1 t2
355 tl = intersection l1 lt
356 tr = intersection r1 gt
357 in if found then join x1 tl tr
360 {--------------------------------------------------------------------
362 --------------------------------------------------------------------}
363 -- | /O(n)/. Filter all elements that satisfy the predicate.
364 filter :: Ord a => (a -> Bool) -> Set a -> Set a
366 filter p (Bin _ x l r)
367 | p x = join x (filter p l) (filter p r)
368 | otherwise = merge (filter p l) (filter p r)
370 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
371 -- the predicate and one with all elements that don't satisfy the predicate.
373 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
374 partition p Tip = (Tip,Tip)
375 partition p (Bin _ x l r)
376 | p x = (join x l1 r1,merge l2 r2)
377 | otherwise = (merge l1 r1,join x l2 r2)
379 (l1,l2) = partition p l
380 (r1,r2) = partition p r
382 {----------------------------------------------------------------------
384 ----------------------------------------------------------------------}
387 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
389 -- It's worth noting that the size of the result may be smaller if,
390 -- for some @(x,y)@, @x \/= y && f x == f y@
392 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
393 map f = fromList . List.map f . toList
397 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
398 -- /The precondition is not checked./
399 -- Semi-formally, we have:
401 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
402 -- > ==> mapMonotonic f s == map f s
403 -- > where ls = toList s
405 mapMonotonic :: (a->b) -> Set a -> Set b
406 mapMonotonic f Tip = Tip
407 mapMonotonic f (Bin sz x l r) =
408 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
411 {--------------------------------------------------------------------
413 --------------------------------------------------------------------}
414 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
415 fold :: (a -> b -> b) -> b -> Set a -> b
419 -- | /O(n)/. Post-order fold.
420 foldr :: (a -> b -> b) -> b -> Set a -> b
422 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
424 {--------------------------------------------------------------------
426 --------------------------------------------------------------------}
427 -- | /O(n)/. The elements of a set.
428 elems :: Set a -> [a]
432 {--------------------------------------------------------------------
434 --------------------------------------------------------------------}
435 -- | /O(n)/. Convert the set to a list of elements.
436 toList :: Set a -> [a]
440 -- | /O(n)/. Convert the set to an ascending list of elements.
441 toAscList :: Set a -> [a]
446 -- | /O(n*log n)/. Create a set from a list of elements.
447 fromList :: Ord a => [a] -> Set a
449 = foldlStrict ins empty xs
453 {--------------------------------------------------------------------
454 Building trees from ascending/descending lists can be done in linear time.
456 Note that if [xs] is ascending that:
457 fromAscList xs == fromList xs
458 --------------------------------------------------------------------}
459 -- | /O(n)/. Build a set from an ascending list in linear time.
460 -- /The precondition (input list is ascending) is not checked./
461 fromAscList :: Eq a => [a] -> Set a
463 = fromDistinctAscList (combineEq xs)
465 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
470 (x:xx) -> combineEq' x xx
472 combineEq' z [] = [z]
474 | z==x = combineEq' z xs
475 | otherwise = z:combineEq' x xs
478 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
479 -- /The precondition (input list is strictly ascending) is not checked./
480 fromDistinctAscList :: [a] -> Set a
481 fromDistinctAscList xs
482 = build const (length xs) xs
484 -- 1) use continutations so that we use heap space instead of stack space.
485 -- 2) special case for n==5 to build bushier trees.
486 build c 0 xs = c Tip xs
487 build c 5 xs = case xs of
489 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
490 build c n xs = seq nr $ build (buildR nr c) nl xs
495 buildR n c l (x:ys) = build (buildB l x c) n ys
496 buildB l x c r zs = c (bin x l r) zs
498 {--------------------------------------------------------------------
499 Eq converts the set to a list. In a lazy setting, this
500 actually seems one of the faster methods to compare two trees
501 and it is certainly the simplest :-)
502 --------------------------------------------------------------------}
503 instance Eq a => Eq (Set a) where
504 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
506 {--------------------------------------------------------------------
508 --------------------------------------------------------------------}
510 instance Ord a => Ord (Set a) where
511 compare s1 s2 = compare (toAscList s1) (toAscList s2)
513 {--------------------------------------------------------------------
515 --------------------------------------------------------------------}
516 instance Show a => Show (Set a) where
517 showsPrec p xs = showParen (p > 10) $
518 showString "fromList " . shows (toList xs)
520 showSet :: (Show a) => [a] -> ShowS
524 = showChar '{' . shows x . showTail xs
526 showTail [] = showChar '}'
527 showTail (x:xs) = showChar ',' . shows x . showTail xs
529 {--------------------------------------------------------------------
531 --------------------------------------------------------------------}
532 instance (Read a, Ord a) => Read (Set a) where
533 #ifdef __GLASGOW_HASKELL__
534 readPrec = parens $ prec 10 $ do
535 Ident "fromList" <- lexP
539 readListPrec = readListPrecDefault
541 readsPrec p = readParen (p > 10) $ \ r -> do
542 ("fromList",s) <- lex r
544 return (fromList xs,t)
547 {--------------------------------------------------------------------
549 --------------------------------------------------------------------}
551 #include "Typeable.h"
552 INSTANCE_TYPEABLE1(Set,setTc,"Set")
554 {--------------------------------------------------------------------
555 Utility functions that return sub-ranges of the original
556 tree. Some functions take a comparison function as argument to
557 allow comparisons against infinite values. A function [cmplo x]
558 should be read as [compare lo x].
560 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
561 and [cmphi x == GT] for the value [x] of the root.
562 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
563 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
565 [split k t] Returns two trees [l] and [r] where all values
566 in [l] are <[k] and all keys in [r] are >[k].
567 [splitMember k t] Just like [split] but also returns whether [k]
568 was found in the tree.
569 --------------------------------------------------------------------}
571 {--------------------------------------------------------------------
572 [trim lo hi t] trims away all subtrees that surely contain no
573 values between the range [lo] to [hi]. The returned tree is either
574 empty or the key of the root is between @lo@ and @hi@.
575 --------------------------------------------------------------------}
576 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
577 trim cmplo cmphi Tip = Tip
578 trim cmplo cmphi t@(Bin sx x l r)
580 LT -> case cmphi x of
582 le -> trim cmplo cmphi l
583 ge -> trim cmplo cmphi r
585 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
586 trimMemberLo lo cmphi Tip = (False,Tip)
587 trimMemberLo lo cmphi t@(Bin sx x l r)
588 = case compare lo x of
589 LT -> case cmphi x of
590 GT -> (member lo t, t)
591 le -> trimMemberLo lo cmphi l
592 GT -> trimMemberLo lo cmphi r
593 EQ -> (True,trim (compare lo) cmphi r)
596 {--------------------------------------------------------------------
597 [filterGt x t] filter all values >[x] from tree [t]
598 [filterLt x t] filter all values <[x] from tree [t]
599 --------------------------------------------------------------------}
600 filterGt :: (a -> Ordering) -> Set a -> Set a
601 filterGt cmp Tip = Tip
602 filterGt cmp (Bin sx x l r)
604 LT -> join x (filterGt cmp l) r
608 filterLt :: (a -> Ordering) -> Set a -> Set a
609 filterLt cmp Tip = Tip
610 filterLt cmp (Bin sx x l r)
613 GT -> join x l (filterLt cmp r)
617 {--------------------------------------------------------------------
619 --------------------------------------------------------------------}
620 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
621 -- where all elements in @set1@ are lower than @x@ and all elements in
622 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
623 split :: Ord a => a -> Set a -> (Set a,Set a)
624 split x Tip = (Tip,Tip)
625 split x (Bin sy y l r)
626 = case compare x y of
627 LT -> let (lt,gt) = split x l in (lt,join y gt r)
628 GT -> let (lt,gt) = split x r in (join y l lt,gt)
631 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
632 -- element was found in the original set.
633 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
634 splitMember x t = let (l,m,r) = splitLookup x t in
635 (l,maybe False (const True) m,r)
637 -- | /O(log n)/. Performs a 'split' but also returns the pivot
638 -- element that was found in the original set.
639 splitLookup :: Ord a => a -> Set a -> (Set a,Maybe a,Set a)
640 splitLookup x Tip = (Tip,Nothing,Tip)
641 splitLookup x (Bin sy y l r)
642 = case compare x y of
643 LT -> let (lt,found,gt) = splitLookup x l in (lt,found,join y gt r)
644 GT -> let (lt,found,gt) = splitLookup x r in (join y l lt,found,gt)
647 {--------------------------------------------------------------------
648 Utility functions that maintain the balance properties of the tree.
649 All constructors assume that all values in [l] < [x] and all values
650 in [r] > [x], and that [l] and [r] are valid trees.
652 In order of sophistication:
653 [Bin sz x l r] The type constructor.
654 [bin x l r] Maintains the correct size, assumes that both [l]
655 and [r] are balanced with respect to each other.
656 [balance x l r] Restores the balance and size.
657 Assumes that the original tree was balanced and
658 that [l] or [r] has changed by at most one element.
659 [join x l r] Restores balance and size.
661 Furthermore, we can construct a new tree from two trees. Both operations
662 assume that all values in [l] < all values in [r] and that [l] and [r]
664 [glue l r] Glues [l] and [r] together. Assumes that [l] and
665 [r] are already balanced with respect to each other.
666 [merge l r] Merges two trees and restores balance.
668 Note: in contrast to Adam's paper, we use (<=) comparisons instead
669 of (<) comparisons in [join], [merge] and [balance].
670 Quickcheck (on [difference]) showed that this was necessary in order
671 to maintain the invariants. It is quite unsatisfactory that I haven't
672 been able to find out why this is actually the case! Fortunately, it
673 doesn't hurt to be a bit more conservative.
674 --------------------------------------------------------------------}
676 {--------------------------------------------------------------------
678 --------------------------------------------------------------------}
679 join :: a -> Set a -> Set a -> Set a
680 join x Tip r = insertMin x r
681 join x l Tip = insertMax x l
682 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
683 | delta*sizeL <= sizeR = balance z (join x l lz) rz
684 | delta*sizeR <= sizeL = balance y ly (join x ry r)
685 | otherwise = bin x l r
688 -- insertMin and insertMax don't perform potentially expensive comparisons.
689 insertMax,insertMin :: a -> Set a -> Set a
694 -> balance y l (insertMax x r)
700 -> balance y (insertMin x l) r
702 {--------------------------------------------------------------------
703 [merge l r]: merges two trees.
704 --------------------------------------------------------------------}
705 merge :: Set a -> Set a -> Set a
708 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
709 | delta*sizeL <= sizeR = balance y (merge l ly) ry
710 | delta*sizeR <= sizeL = balance x lx (merge rx r)
711 | otherwise = glue l r
713 {--------------------------------------------------------------------
714 [glue l r]: glues two trees together.
715 Assumes that [l] and [r] are already balanced with respect to each other.
716 --------------------------------------------------------------------}
717 glue :: Set a -> Set a -> Set a
721 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
722 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
725 -- | /O(log n)/. Delete and find the minimal element.
727 -- > deleteFindMin set = (findMin set, deleteMin set)
729 deleteFindMin :: Set a -> (a,Set a)
732 Bin _ x Tip r -> (x,r)
733 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
734 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
736 -- | /O(log n)/. Delete and find the maximal element.
738 -- > deleteFindMax set = (findMax set, deleteMax set)
739 deleteFindMax :: Set a -> (a,Set a)
742 Bin _ x l Tip -> (x,l)
743 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
744 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
746 -- | /O(log n)/. Retrieves the minimal key of the set, and the set stripped from that element
747 -- @fail@s (in the monad) when passed an empty set.
748 minView :: Monad m => Set a -> m (Set a, a)
749 minView Tip = fail "Set.minView: empty set"
750 minView x = return (swap $ deleteFindMin x)
752 -- | /O(log n)/. Retrieves the maximal key of the set, and the set stripped from that element
753 -- @fail@s (in the monad) when passed an empty set.
754 maxView :: Monad m => Set a -> m (Set a, a)
755 maxView Tip = fail "Set.maxView: empty set"
756 maxView x = return (swap $ deleteFindMax x)
762 {--------------------------------------------------------------------
763 [balance x l r] balances two trees with value x.
764 The sizes of the trees should balance after decreasing the
765 size of one of them. (a rotation).
767 [delta] is the maximal relative difference between the sizes of
768 two trees, it corresponds with the [w] in Adams' paper,
769 or equivalently, [1/delta] corresponds with the $\alpha$
770 in Nievergelt's paper. Adams shows that [delta] should
771 be larger than 3.745 in order to garantee that the
772 rotations can always restore balance.
774 [ratio] is the ratio between an outer and inner sibling of the
775 heavier subtree in an unbalanced setting. It determines
776 whether a double or single rotation should be performed
777 to restore balance. It is correspondes with the inverse
778 of $\alpha$ in Adam's article.
781 - [delta] should be larger than 4.646 with a [ratio] of 2.
782 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
784 - A lower [delta] leads to a more 'perfectly' balanced tree.
785 - A higher [delta] performs less rebalancing.
787 - Balancing is automatic for random data and a balancing
788 scheme is only necessary to avoid pathological worst cases.
789 Almost any choice will do in practice
791 - Allthough it seems that a rather large [delta] may perform better
792 than smaller one, measurements have shown that the smallest [delta]
793 of 4 is actually the fastest on a wide range of operations. It
794 especially improves performance on worst-case scenarios like
795 a sequence of ordered insertions.
797 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
798 to decide whether a single or double rotation is needed. Allthough
799 he actually proves that this ratio is needed to maintain the
800 invariants, his implementation uses a (invalid) ratio of 1.
801 He is aware of the problem though since he has put a comment in his
802 original source code that he doesn't care about generating a
803 slightly inbalanced tree since it doesn't seem to matter in practice.
804 However (since we use quickcheck :-) we will stick to strictly balanced
806 --------------------------------------------------------------------}
811 balance :: a -> Set a -> Set a -> Set a
813 | sizeL + sizeR <= 1 = Bin sizeX x l r
814 | sizeR >= delta*sizeL = rotateL x l r
815 | sizeL >= delta*sizeR = rotateR x l r
816 | otherwise = Bin sizeX x l r
820 sizeX = sizeL + sizeR + 1
823 rotateL x l r@(Bin _ _ ly ry)
824 | size ly < ratio*size ry = singleL x l r
825 | otherwise = doubleL x l r
827 rotateR x l@(Bin _ _ ly ry) r
828 | size ry < ratio*size ly = singleR x l r
829 | otherwise = doubleR x l r
832 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
833 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
835 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
836 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
839 {--------------------------------------------------------------------
840 The bin constructor maintains the size of the tree
841 --------------------------------------------------------------------}
842 bin :: a -> Set a -> Set a -> Set a
844 = Bin (size l + size r + 1) x l r
847 {--------------------------------------------------------------------
849 --------------------------------------------------------------------}
853 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
856 {--------------------------------------------------------------------
858 --------------------------------------------------------------------}
859 -- | /O(n)/. Show the tree that implements the set. The tree is shown
860 -- in a compressed, hanging format.
861 showTree :: Show a => Set a -> String
863 = showTreeWith True False s
866 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
867 the tree that implements the set. If @hang@ is
868 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
869 @wide@ is 'True', an extra wide version is shown.
871 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
878 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
889 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
901 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
902 showTreeWith hang wide t
903 | hang = (showsTreeHang wide [] t) ""
904 | otherwise = (showsTree wide [] [] t) ""
906 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
907 showsTree wide lbars rbars t
909 Tip -> showsBars lbars . showString "|\n"
911 -> showsBars lbars . shows x . showString "\n"
913 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
914 showWide wide rbars .
915 showsBars lbars . shows x . showString "\n" .
916 showWide wide lbars .
917 showsTree wide (withEmpty lbars) (withBar lbars) l
919 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
920 showsTreeHang wide bars t
922 Tip -> showsBars bars . showString "|\n"
924 -> showsBars bars . shows x . showString "\n"
926 -> showsBars bars . shows x . showString "\n" .
928 showsTreeHang wide (withBar bars) l .
930 showsTreeHang wide (withEmpty bars) r
934 | wide = showString (concat (reverse bars)) . showString "|\n"
937 showsBars :: [String] -> ShowS
941 _ -> showString (concat (reverse (tail bars))) . showString node
944 withBar bars = "| ":bars
945 withEmpty bars = " ":bars
947 {--------------------------------------------------------------------
949 --------------------------------------------------------------------}
950 -- | /O(n)/. Test if the internal set structure is valid.
951 valid :: Ord a => Set a -> Bool
953 = balanced t && ordered t && validsize t
956 = bounded (const True) (const True) t
961 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
963 balanced :: Set a -> Bool
967 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
968 balanced l && balanced r
972 = (realsize t == Just (size t))
977 Bin sz x l r -> case (realsize l,realsize r) of
978 (Just n,Just m) | n+m+1 == sz -> Just sz
982 {--------------------------------------------------------------------
984 --------------------------------------------------------------------}
985 testTree :: [Int] -> Set Int
986 testTree xs = fromList xs
987 test1 = testTree [1..20]
988 test2 = testTree [30,29..10]
989 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
991 {--------------------------------------------------------------------
993 --------------------------------------------------------------------}
998 { configMaxTest = 500
999 , configMaxFail = 5000
1000 , configSize = \n -> (div n 2 + 3)
1001 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1005 {--------------------------------------------------------------------
1006 Arbitrary, reasonably balanced trees
1007 --------------------------------------------------------------------}
1008 instance (Enum a) => Arbitrary (Set a) where
1009 arbitrary = sized (arbtree 0 maxkey)
1010 where maxkey = 10000
1012 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
1014 | n <= 0 = return Tip
1015 | lo >= hi = return Tip
1016 | otherwise = do{ i <- choose (lo,hi)
1017 ; m <- choose (1,30)
1018 ; let (ml,mr) | m==(1::Int)= (1,2)
1022 ; l <- arbtree lo (i-1) (n `div` ml)
1023 ; r <- arbtree (i+1) hi (n `div` mr)
1024 ; return (bin (toEnum i) l r)
1028 {--------------------------------------------------------------------
1030 --------------------------------------------------------------------}
1031 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1033 = forAll arbitrary $ \t ->
1034 -- classify (balanced t) "balanced" $
1035 classify (size t == 0) "empty" $
1036 classify (size t > 0 && size t <= 10) "small" $
1037 classify (size t > 10 && size t <= 64) "medium" $
1038 classify (size t > 64) "large" $
1041 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1045 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1051 = forValidUnitTree $ \t -> valid t
1053 {--------------------------------------------------------------------
1054 Single, Insert, Delete
1055 --------------------------------------------------------------------}
1056 prop_Single :: Int -> Bool
1058 = (insert x empty == singleton x)
1060 prop_InsertValid :: Int -> Property
1062 = forValidUnitTree $ \t -> valid (insert k t)
1064 prop_InsertDelete :: Int -> Set Int -> Property
1065 prop_InsertDelete k t
1066 = not (member k t) ==> delete k (insert k t) == t
1068 prop_DeleteValid :: Int -> Property
1070 = forValidUnitTree $ \t ->
1071 valid (delete k (insert k t))
1073 {--------------------------------------------------------------------
1075 --------------------------------------------------------------------}
1076 prop_Join :: Int -> Property
1078 = forValidUnitTree $ \t ->
1079 let (l,r) = split x t
1080 in valid (join x l r)
1082 prop_Merge :: Int -> Property
1084 = forValidUnitTree $ \t ->
1085 let (l,r) = split x t
1086 in valid (merge l r)
1089 {--------------------------------------------------------------------
1091 --------------------------------------------------------------------}
1092 prop_UnionValid :: Property
1094 = forValidUnitTree $ \t1 ->
1095 forValidUnitTree $ \t2 ->
1098 prop_UnionInsert :: Int -> Set Int -> Bool
1099 prop_UnionInsert x t
1100 = union t (singleton x) == insert x t
1102 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1103 prop_UnionAssoc t1 t2 t3
1104 = union t1 (union t2 t3) == union (union t1 t2) t3
1106 prop_UnionComm :: Set Int -> Set Int -> Bool
1107 prop_UnionComm t1 t2
1108 = (union t1 t2 == union t2 t1)
1112 = forValidUnitTree $ \t1 ->
1113 forValidUnitTree $ \t2 ->
1114 valid (difference t1 t2)
1116 prop_Diff :: [Int] -> [Int] -> Bool
1118 = toAscList (difference (fromList xs) (fromList ys))
1119 == List.sort ((List.\\) (nub xs) (nub ys))
1122 = forValidUnitTree $ \t1 ->
1123 forValidUnitTree $ \t2 ->
1124 valid (intersection t1 t2)
1126 prop_Int :: [Int] -> [Int] -> Bool
1128 = toAscList (intersection (fromList xs) (fromList ys))
1129 == List.sort (nub ((List.intersect) (xs) (ys)))
1131 {--------------------------------------------------------------------
1133 --------------------------------------------------------------------}
1135 = forAll (choose (5,100)) $ \n ->
1136 let xs = [0..n::Int]
1137 in fromAscList xs == fromList xs
1139 prop_List :: [Int] -> Bool
1141 = (sort (nub xs) == toList (fromList xs))