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,Ord,Show,Read,Data,Typeable
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,null,map)
115 import qualified Data.List as List
121 import List (nub,sort)
122 import qualified List
125 #if __GLASGOW_HASKELL__
127 import Data.Generics.Basics
128 import Data.Generics.Instances
131 {--------------------------------------------------------------------
133 --------------------------------------------------------------------}
136 -- | /O(n+m)/. See 'difference'.
137 (\\) :: Ord a => Set a -> Set a -> Set a
138 m1 \\ m2 = difference m1 m2
140 {--------------------------------------------------------------------
141 Sets are size balanced trees
142 --------------------------------------------------------------------}
143 -- | A set of values @a@.
145 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
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"
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 {--------------------------------------------------------------------
196 --------------------------------------------------------------------}
197 -- | /O(1)/. The empty set.
202 -- | /O(1)/. Create a singleton set.
203 singleton :: a -> Set a
207 {--------------------------------------------------------------------
209 --------------------------------------------------------------------}
210 -- | /O(log n)/. Insert an element in a set.
211 -- If the set already contains an element equal to the given value,
212 -- it is replaced with the new value.
213 insert :: Ord a => a -> Set a -> Set a
218 -> case compare x y of
219 LT -> balance y (insert x l) r
220 GT -> balance y l (insert x r)
224 -- | /O(log n)/. Delete an element from a set.
225 delete :: Ord a => a -> Set a -> Set a
230 -> case compare x y of
231 LT -> balance y (delete x l) r
232 GT -> balance y l (delete x r)
235 {--------------------------------------------------------------------
237 --------------------------------------------------------------------}
238 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
239 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
240 isProperSubsetOf s1 s2
241 = (size s1 < size s2) && (isSubsetOf s1 s2)
244 -- | /O(n+m)/. Is this a subset?
245 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
246 isSubsetOf :: Ord a => Set a -> Set a -> Bool
248 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
250 isSubsetOfX Tip t = True
251 isSubsetOfX t Tip = False
252 isSubsetOfX (Bin _ x l r) t
253 = found && isSubsetOfX l lt && isSubsetOfX r gt
255 (lt,found,gt) = splitMember x t
258 {--------------------------------------------------------------------
260 --------------------------------------------------------------------}
261 -- | /O(log n)/. The minimal element of a set.
262 findMin :: Set a -> a
263 findMin (Bin _ x Tip r) = x
264 findMin (Bin _ x l r) = findMin l
265 findMin Tip = error "Set.findMin: empty set has no minimal element"
267 -- | /O(log n)/. The maximal element of a set.
268 findMax :: Set a -> a
269 findMax (Bin _ x l Tip) = x
270 findMax (Bin _ x l r) = findMax r
271 findMax Tip = error "Set.findMax: empty set has no maximal element"
273 -- | /O(log n)/. Delete the minimal element.
274 deleteMin :: Set a -> Set a
275 deleteMin (Bin _ x Tip r) = r
276 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
279 -- | /O(log n)/. Delete the maximal element.
280 deleteMax :: Set a -> Set a
281 deleteMax (Bin _ x l Tip) = l
282 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
286 {--------------------------------------------------------------------
288 --------------------------------------------------------------------}
289 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
290 unions :: Ord a => [Set a] -> Set a
292 = foldlStrict union empty ts
295 -- | /O(n+m)/. The union of two sets, preferring the first set when
296 -- equal elements are encountered.
297 -- The implementation uses the efficient /hedge-union/ algorithm.
298 -- Hedge-union is more efficient on (bigset `union` smallset).
299 union :: Ord a => Set a -> Set a -> Set a
303 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
304 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
306 hedgeUnion cmplo cmphi t1 Tip
308 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
309 = join x (filterGt cmplo l) (filterLt cmphi r)
310 hedgeUnion cmplo cmphi (Bin _ x l r) t2
311 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
312 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
316 {--------------------------------------------------------------------
318 --------------------------------------------------------------------}
319 -- | /O(n+m)/. Difference of two sets.
320 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
321 difference :: Ord a => Set a -> Set a -> Set a
322 difference Tip t2 = Tip
323 difference t1 Tip = t1
324 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
326 hedgeDiff cmplo cmphi Tip t
328 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
329 = join x (filterGt cmplo l) (filterLt cmphi r)
330 hedgeDiff cmplo cmphi t (Bin _ x l r)
331 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
332 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
336 {--------------------------------------------------------------------
338 --------------------------------------------------------------------}
339 -- | /O(n+m)/. The intersection of two sets.
340 -- Intersection is more efficient on (bigset `intersection` smallset).
341 intersection :: Ord a => Set a -> Set a -> Set a
342 intersection Tip t = Tip
343 intersection t Tip = Tip
345 | size t1 >= size t2 = intersect' t1 t2
346 | otherwise = intersect' t2 t1
348 intersect' Tip t = Tip
349 intersect' t Tip = Tip
350 intersect' t (Bin _ x l r)
351 | found = join x tl tr
352 | otherwise = merge tl tr
354 (lt,found,gt) = splitMember x t
359 {--------------------------------------------------------------------
361 --------------------------------------------------------------------}
362 -- | /O(n)/. Filter all elements that satisfy the predicate.
363 filter :: Ord a => (a -> Bool) -> Set a -> Set a
365 filter p (Bin _ x l r)
366 | p x = join x (filter p l) (filter p r)
367 | otherwise = merge (filter p l) (filter p r)
369 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
370 -- the predicate and one with all elements that don't satisfy the predicate.
372 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
373 partition p Tip = (Tip,Tip)
374 partition p (Bin _ x l r)
375 | p x = (join x l1 r1,merge l2 r2)
376 | otherwise = (merge l1 r1,join x l2 r2)
378 (l1,l2) = partition p l
379 (r1,r2) = partition p r
381 {----------------------------------------------------------------------
383 ----------------------------------------------------------------------}
386 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
388 -- It's worth noting that the size of the result may be smaller if,
389 -- for some @(x,y)@, @x \/= y && f x == f y@
391 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
392 map f = fromList . List.map f . toList
396 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
397 -- /The precondition is not checked./
398 -- Semi-formally, we have:
400 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
401 -- > ==> mapMonotonic f s == map f s
402 -- > where ls = toList s
404 mapMonotonic :: (a->b) -> Set a -> Set b
405 mapMonotonic f Tip = Tip
406 mapMonotonic f (Bin sz x l r) =
407 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
410 {--------------------------------------------------------------------
412 --------------------------------------------------------------------}
413 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
414 fold :: (a -> b -> b) -> b -> Set a -> b
418 -- | /O(n)/. Post-order fold.
419 foldr :: (a -> b -> b) -> b -> Set a -> b
421 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
423 {--------------------------------------------------------------------
425 --------------------------------------------------------------------}
426 -- | /O(n)/. The elements of a set.
427 elems :: Set a -> [a]
431 {--------------------------------------------------------------------
433 --------------------------------------------------------------------}
434 -- | /O(n)/. Convert the set to a list of elements.
435 toList :: Set a -> [a]
439 -- | /O(n)/. Convert the set to an ascending list of elements.
440 toAscList :: Set a -> [a]
445 -- | /O(n*log n)/. Create a set from a list of elements.
446 fromList :: Ord a => [a] -> Set a
448 = foldlStrict ins empty xs
452 {--------------------------------------------------------------------
453 Building trees from ascending/descending lists can be done in linear time.
455 Note that if [xs] is ascending that:
456 fromAscList xs == fromList xs
457 --------------------------------------------------------------------}
458 -- | /O(n)/. Build a set from an ascending list in linear time.
459 -- /The precondition (input list is ascending) is not checked./
460 fromAscList :: Eq a => [a] -> Set a
462 = fromDistinctAscList (combineEq xs)
464 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
469 (x:xx) -> combineEq' x xx
471 combineEq' z [] = [z]
473 | z==x = combineEq' z xs
474 | otherwise = z:combineEq' x xs
477 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
478 -- /The precondition (input list is strictly ascending) is not checked./
479 fromDistinctAscList :: [a] -> Set a
480 fromDistinctAscList xs
481 = build const (length xs) xs
483 -- 1) use continutations so that we use heap space instead of stack space.
484 -- 2) special case for n==5 to build bushier trees.
485 build c 0 xs = c Tip xs
486 build c 5 xs = case xs of
488 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
489 build c n xs = seq nr $ build (buildR nr c) nl xs
494 buildR n c l (x:ys) = build (buildB l x c) n ys
495 buildB l x c r zs = c (bin x l r) zs
497 {--------------------------------------------------------------------
498 Eq converts the set to a list. In a lazy setting, this
499 actually seems one of the faster methods to compare two trees
500 and it is certainly the simplest :-)
501 --------------------------------------------------------------------}
502 instance Eq a => Eq (Set a) where
503 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
505 {--------------------------------------------------------------------
507 --------------------------------------------------------------------}
509 instance Ord a => Ord (Set a) where
510 compare s1 s2 = compare (toAscList s1) (toAscList s2)
512 {--------------------------------------------------------------------
514 --------------------------------------------------------------------}
515 instance Show a => Show (Set a) where
516 showsPrec p xs = showParen (p > 10) $
517 showString "fromList " . shows (toList xs)
519 showSet :: (Show a) => [a] -> ShowS
523 = showChar '{' . shows x . showTail xs
525 showTail [] = showChar '}'
526 showTail (x:xs) = showChar ',' . shows x . showTail xs
528 {--------------------------------------------------------------------
530 --------------------------------------------------------------------}
531 instance (Read a, Ord a) => Read (Set a) where
532 #ifdef __GLASGOW_HASKELL__
533 readPrec = parens $ prec 10 $ do
534 Ident "fromList" <- lexP
538 readListPrec = readListPrecDefault
540 readsPrec p = readParen (p > 10) $ \ r -> do
541 ("fromList",s) <- lex r
543 return (fromList xs,t)
546 {--------------------------------------------------------------------
548 --------------------------------------------------------------------}
550 #include "Typeable.h"
551 INSTANCE_TYPEABLE1(Set,setTc,"Set")
553 {--------------------------------------------------------------------
554 Utility functions that return sub-ranges of the original
555 tree. Some functions take a comparison function as argument to
556 allow comparisons against infinite values. A function [cmplo x]
557 should be read as [compare lo x].
559 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
560 and [cmphi x == GT] for the value [x] of the root.
561 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
562 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
564 [split k t] Returns two trees [l] and [r] where all values
565 in [l] are <[k] and all keys in [r] are >[k].
566 [splitMember k t] Just like [split] but also returns whether [k]
567 was found in the tree.
568 --------------------------------------------------------------------}
570 {--------------------------------------------------------------------
571 [trim lo hi t] trims away all subtrees that surely contain no
572 values between the range [lo] to [hi]. The returned tree is either
573 empty or the key of the root is between @lo@ and @hi@.
574 --------------------------------------------------------------------}
575 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
576 trim cmplo cmphi Tip = Tip
577 trim cmplo cmphi t@(Bin sx x l r)
579 LT -> case cmphi x of
581 le -> trim cmplo cmphi l
582 ge -> trim cmplo cmphi r
584 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
585 trimMemberLo lo cmphi Tip = (False,Tip)
586 trimMemberLo lo cmphi t@(Bin sx x l r)
587 = case compare lo x of
588 LT -> case cmphi x of
589 GT -> (member lo t, t)
590 le -> trimMemberLo lo cmphi l
591 GT -> trimMemberLo lo cmphi r
592 EQ -> (True,trim (compare lo) cmphi r)
595 {--------------------------------------------------------------------
596 [filterGt x t] filter all values >[x] from tree [t]
597 [filterLt x t] filter all values <[x] from tree [t]
598 --------------------------------------------------------------------}
599 filterGt :: (a -> Ordering) -> Set a -> Set a
600 filterGt cmp Tip = Tip
601 filterGt cmp (Bin sx x l r)
603 LT -> join x (filterGt cmp l) r
607 filterLt :: (a -> Ordering) -> Set a -> Set a
608 filterLt cmp Tip = Tip
609 filterLt cmp (Bin sx x l r)
612 GT -> join x l (filterLt cmp r)
616 {--------------------------------------------------------------------
618 --------------------------------------------------------------------}
619 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
620 -- where all elements in @set1@ are lower than @x@ and all elements in
621 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
622 split :: Ord a => a -> Set a -> (Set a,Set a)
623 split x Tip = (Tip,Tip)
624 split x (Bin sy y l r)
625 = case compare x y of
626 LT -> let (lt,gt) = split x l in (lt,join y gt r)
627 GT -> let (lt,gt) = split x r in (join y l lt,gt)
630 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
631 -- element was found in the original set.
632 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
633 splitMember x Tip = (Tip,False,Tip)
634 splitMember x (Bin sy y l r)
635 = case compare x y of
636 LT -> let (lt,found,gt) = splitMember x l in (lt,found,join y gt r)
637 GT -> let (lt,found,gt) = splitMember x r in (join y l lt,found,gt)
640 {--------------------------------------------------------------------
641 Utility functions that maintain the balance properties of the tree.
642 All constructors assume that all values in [l] < [x] and all values
643 in [r] > [x], and that [l] and [r] are valid trees.
645 In order of sophistication:
646 [Bin sz x l r] The type constructor.
647 [bin x l r] Maintains the correct size, assumes that both [l]
648 and [r] are balanced with respect to each other.
649 [balance x l r] Restores the balance and size.
650 Assumes that the original tree was balanced and
651 that [l] or [r] has changed by at most one element.
652 [join x l r] Restores balance and size.
654 Furthermore, we can construct a new tree from two trees. Both operations
655 assume that all values in [l] < all values in [r] and that [l] and [r]
657 [glue l r] Glues [l] and [r] together. Assumes that [l] and
658 [r] are already balanced with respect to each other.
659 [merge l r] Merges two trees and restores balance.
661 Note: in contrast to Adam's paper, we use (<=) comparisons instead
662 of (<) comparisons in [join], [merge] and [balance].
663 Quickcheck (on [difference]) showed that this was necessary in order
664 to maintain the invariants. It is quite unsatisfactory that I haven't
665 been able to find out why this is actually the case! Fortunately, it
666 doesn't hurt to be a bit more conservative.
667 --------------------------------------------------------------------}
669 {--------------------------------------------------------------------
671 --------------------------------------------------------------------}
672 join :: a -> Set a -> Set a -> Set a
673 join x Tip r = insertMin x r
674 join x l Tip = insertMax x l
675 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
676 | delta*sizeL <= sizeR = balance z (join x l lz) rz
677 | delta*sizeR <= sizeL = balance y ly (join x ry r)
678 | otherwise = bin x l r
681 -- insertMin and insertMax don't perform potentially expensive comparisons.
682 insertMax,insertMin :: a -> Set a -> Set a
687 -> balance y l (insertMax x r)
693 -> balance y (insertMin x l) r
695 {--------------------------------------------------------------------
696 [merge l r]: merges two trees.
697 --------------------------------------------------------------------}
698 merge :: Set a -> Set a -> Set a
701 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
702 | delta*sizeL <= sizeR = balance y (merge l ly) ry
703 | delta*sizeR <= sizeL = balance x lx (merge rx r)
704 | otherwise = glue l r
706 {--------------------------------------------------------------------
707 [glue l r]: glues two trees together.
708 Assumes that [l] and [r] are already balanced with respect to each other.
709 --------------------------------------------------------------------}
710 glue :: Set a -> Set a -> Set a
714 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
715 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
718 -- | /O(log n)/. Delete and find the minimal element.
720 -- > deleteFindMin set = (findMin set, deleteMin set)
722 deleteFindMin :: Set a -> (a,Set a)
725 Bin _ x Tip r -> (x,r)
726 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
727 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
729 -- | /O(log n)/. Delete and find the maximal element.
731 -- > deleteFindMax set = (findMax set, deleteMax set)
732 deleteFindMax :: Set a -> (a,Set a)
735 Bin _ x l Tip -> (x,l)
736 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
737 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
740 {--------------------------------------------------------------------
741 [balance x l r] balances two trees with value x.
742 The sizes of the trees should balance after decreasing the
743 size of one of them. (a rotation).
745 [delta] is the maximal relative difference between the sizes of
746 two trees, it corresponds with the [w] in Adams' paper,
747 or equivalently, [1/delta] corresponds with the $\alpha$
748 in Nievergelt's paper. Adams shows that [delta] should
749 be larger than 3.745 in order to garantee that the
750 rotations can always restore balance.
752 [ratio] is the ratio between an outer and inner sibling of the
753 heavier subtree in an unbalanced setting. It determines
754 whether a double or single rotation should be performed
755 to restore balance. It is correspondes with the inverse
756 of $\alpha$ in Adam's article.
759 - [delta] should be larger than 4.646 with a [ratio] of 2.
760 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
762 - A lower [delta] leads to a more 'perfectly' balanced tree.
763 - A higher [delta] performs less rebalancing.
765 - Balancing is automatic for random data and a balancing
766 scheme is only necessary to avoid pathological worst cases.
767 Almost any choice will do in practice
769 - Allthough it seems that a rather large [delta] may perform better
770 than smaller one, measurements have shown that the smallest [delta]
771 of 4 is actually the fastest on a wide range of operations. It
772 especially improves performance on worst-case scenarios like
773 a sequence of ordered insertions.
775 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
776 to decide whether a single or double rotation is needed. Allthough
777 he actually proves that this ratio is needed to maintain the
778 invariants, his implementation uses a (invalid) ratio of 1.
779 He is aware of the problem though since he has put a comment in his
780 original source code that he doesn't care about generating a
781 slightly inbalanced tree since it doesn't seem to matter in practice.
782 However (since we use quickcheck :-) we will stick to strictly balanced
784 --------------------------------------------------------------------}
789 balance :: a -> Set a -> Set a -> Set a
791 | sizeL + sizeR <= 1 = Bin sizeX x l r
792 | sizeR >= delta*sizeL = rotateL x l r
793 | sizeL >= delta*sizeR = rotateR x l r
794 | otherwise = Bin sizeX x l r
798 sizeX = sizeL + sizeR + 1
801 rotateL x l r@(Bin _ _ ly ry)
802 | size ly < ratio*size ry = singleL x l r
803 | otherwise = doubleL x l r
805 rotateR x l@(Bin _ _ ly ry) r
806 | size ry < ratio*size ly = singleR x l r
807 | otherwise = doubleR x l r
810 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
811 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
813 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
814 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
817 {--------------------------------------------------------------------
818 The bin constructor maintains the size of the tree
819 --------------------------------------------------------------------}
820 bin :: a -> Set a -> Set a -> Set a
822 = Bin (size l + size r + 1) x l r
825 {--------------------------------------------------------------------
827 --------------------------------------------------------------------}
831 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
834 {--------------------------------------------------------------------
836 --------------------------------------------------------------------}
837 -- | /O(n)/. Show the tree that implements the set. The tree is shown
838 -- in a compressed, hanging format.
839 showTree :: Show a => Set a -> String
841 = showTreeWith True False s
844 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
845 the tree that implements the set. If @hang@ is
846 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
847 @wide@ is 'True', an extra wide version is shown.
849 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
856 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
867 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
879 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
880 showTreeWith hang wide t
881 | hang = (showsTreeHang wide [] t) ""
882 | otherwise = (showsTree wide [] [] t) ""
884 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
885 showsTree wide lbars rbars t
887 Tip -> showsBars lbars . showString "|\n"
889 -> showsBars lbars . shows x . showString "\n"
891 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
892 showWide wide rbars .
893 showsBars lbars . shows x . showString "\n" .
894 showWide wide lbars .
895 showsTree wide (withEmpty lbars) (withBar lbars) l
897 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
898 showsTreeHang wide bars t
900 Tip -> showsBars bars . showString "|\n"
902 -> showsBars bars . shows x . showString "\n"
904 -> showsBars bars . shows x . showString "\n" .
906 showsTreeHang wide (withBar bars) l .
908 showsTreeHang wide (withEmpty bars) r
912 | wide = showString (concat (reverse bars)) . showString "|\n"
915 showsBars :: [String] -> ShowS
919 _ -> showString (concat (reverse (tail bars))) . showString node
922 withBar bars = "| ":bars
923 withEmpty bars = " ":bars
925 {--------------------------------------------------------------------
927 --------------------------------------------------------------------}
928 -- | /O(n)/. Test if the internal set structure is valid.
929 valid :: Ord a => Set a -> Bool
931 = balanced t && ordered t && validsize t
934 = bounded (const True) (const True) t
939 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
941 balanced :: Set a -> Bool
945 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
946 balanced l && balanced r
950 = (realsize t == Just (size t))
955 Bin sz x l r -> case (realsize l,realsize r) of
956 (Just n,Just m) | n+m+1 == sz -> Just sz
960 {--------------------------------------------------------------------
962 --------------------------------------------------------------------}
963 testTree :: [Int] -> Set Int
964 testTree xs = fromList xs
965 test1 = testTree [1..20]
966 test2 = testTree [30,29..10]
967 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
969 {--------------------------------------------------------------------
971 --------------------------------------------------------------------}
976 { configMaxTest = 500
977 , configMaxFail = 5000
978 , configSize = \n -> (div n 2 + 3)
979 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
983 {--------------------------------------------------------------------
984 Arbitrary, reasonably balanced trees
985 --------------------------------------------------------------------}
986 instance (Enum a) => Arbitrary (Set a) where
987 arbitrary = sized (arbtree 0 maxkey)
990 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
992 | n <= 0 = return Tip
993 | lo >= hi = return Tip
994 | otherwise = do{ i <- choose (lo,hi)
996 ; let (ml,mr) | m==(1::Int)= (1,2)
1000 ; l <- arbtree lo (i-1) (n `div` ml)
1001 ; r <- arbtree (i+1) hi (n `div` mr)
1002 ; return (bin (toEnum i) l r)
1006 {--------------------------------------------------------------------
1008 --------------------------------------------------------------------}
1009 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1011 = forAll arbitrary $ \t ->
1012 -- classify (balanced t) "balanced" $
1013 classify (size t == 0) "empty" $
1014 classify (size t > 0 && size t <= 10) "small" $
1015 classify (size t > 10 && size t <= 64) "medium" $
1016 classify (size t > 64) "large" $
1019 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1023 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1029 = forValidUnitTree $ \t -> valid t
1031 {--------------------------------------------------------------------
1032 Single, Insert, Delete
1033 --------------------------------------------------------------------}
1034 prop_Single :: Int -> Bool
1036 = (insert x empty == singleton x)
1038 prop_InsertValid :: Int -> Property
1040 = forValidUnitTree $ \t -> valid (insert k t)
1042 prop_InsertDelete :: Int -> Set Int -> Property
1043 prop_InsertDelete k t
1044 = not (member k t) ==> delete k (insert k t) == t
1046 prop_DeleteValid :: Int -> Property
1048 = forValidUnitTree $ \t ->
1049 valid (delete k (insert k t))
1051 {--------------------------------------------------------------------
1053 --------------------------------------------------------------------}
1054 prop_Join :: Int -> Property
1056 = forValidUnitTree $ \t ->
1057 let (l,r) = split x t
1058 in valid (join x l r)
1060 prop_Merge :: Int -> Property
1062 = forValidUnitTree $ \t ->
1063 let (l,r) = split x t
1064 in valid (merge l r)
1067 {--------------------------------------------------------------------
1069 --------------------------------------------------------------------}
1070 prop_UnionValid :: Property
1072 = forValidUnitTree $ \t1 ->
1073 forValidUnitTree $ \t2 ->
1076 prop_UnionInsert :: Int -> Set Int -> Bool
1077 prop_UnionInsert x t
1078 = union t (singleton x) == insert x t
1080 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1081 prop_UnionAssoc t1 t2 t3
1082 = union t1 (union t2 t3) == union (union t1 t2) t3
1084 prop_UnionComm :: Set Int -> Set Int -> Bool
1085 prop_UnionComm t1 t2
1086 = (union t1 t2 == union t2 t1)
1090 = forValidUnitTree $ \t1 ->
1091 forValidUnitTree $ \t2 ->
1092 valid (difference t1 t2)
1094 prop_Diff :: [Int] -> [Int] -> Bool
1096 = toAscList (difference (fromList xs) (fromList ys))
1097 == List.sort ((List.\\) (nub xs) (nub ys))
1100 = forValidUnitTree $ \t1 ->
1101 forValidUnitTree $ \t2 ->
1102 valid (intersection t1 t2)
1104 prop_Int :: [Int] -> [Int] -> Bool
1106 = toAscList (intersection (fromList xs) (fromList ys))
1107 == List.sort (nub ((List.intersect) (xs) (ys)))
1109 {--------------------------------------------------------------------
1111 --------------------------------------------------------------------}
1113 = forAll (choose (5,100)) $ \n ->
1114 let xs = [0..n::Int]
1115 in fromAscList xs == fromList xs
1117 prop_List :: [Int] -> Bool
1119 = (sort (nub xs) == toList (fromList xs))
1122 {--------------------------------------------------------------------
1123 Old Data.Set compatibility interface
1124 --------------------------------------------------------------------}
1126 {-# DEPRECATED emptySet "Use empty instead" #-}
1127 -- | Obsolete equivalent of 'empty'.
1131 {-# DEPRECATED mkSet "Use fromList instead" #-}
1132 -- | Obsolete equivalent of 'fromList'.
1133 mkSet :: Ord a => [a] -> Set a
1136 {-# DEPRECATED setToList "Use elems instead." #-}
1137 -- | Obsolete equivalent of 'elems'.
1138 setToList :: Set a -> [a]
1141 {-# DEPRECATED unitSet "Use singleton instead." #-}
1142 -- | Obsolete equivalent of 'singleton'.
1143 unitSet :: a -> Set a
1146 {-# DEPRECATED elementOf "Use member instead." #-}
1147 -- | Obsolete equivalent of 'member'.
1148 elementOf :: Ord a => a -> Set a -> Bool
1151 {-# DEPRECATED isEmptySet "Use null instead." #-}
1152 -- | Obsolete equivalent of 'null'.
1153 isEmptySet :: Set a -> Bool
1156 {-# DEPRECATED cardinality "Use size instead." #-}
1157 -- | Obsolete equivalent of 'size'.
1158 cardinality :: Set a -> Int
1161 {-# DEPRECATED unionManySets "Use unions instead." #-}
1162 -- | Obsolete equivalent of 'unions'.
1163 unionManySets :: Ord a => [Set a] -> Set a
1164 unionManySets = unions
1166 {-# DEPRECATED minusSet "Use difference instead." #-}
1167 -- | Obsolete equivalent of 'difference'.
1168 minusSet :: Ord a => Set a -> Set a -> Set a
1169 minusSet = difference
1171 {-# DEPRECATED mapSet "Use map instead." #-}
1172 -- | Obsolete equivalent of 'map'.
1173 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1176 {-# DEPRECATED intersect "Use intersection instead." #-}
1177 -- | Obsolete equivalent of 'intersection'.
1178 intersect :: Ord a => Set a -> Set a -> Set a
1179 intersect = intersection
1181 {-# DEPRECATED addToSet "Use 'flip insert' instead." #-}
1182 -- | Obsolete equivalent of @'flip' 'insert'@.
1183 addToSet :: Ord a => Set a -> a -> Set a
1184 addToSet = flip insert
1186 {-# DEPRECATED delFromSet "Use `flip delete' instead." #-}
1187 -- | Obsolete equivalent of @'flip' 'delete'@.
1188 delFromSet :: Ord a => Set a -> a -> Set a
1189 delFromSet = flip delete