[project @ 2005-10-25 09:29:16 by ross]
[ghc.git] / libraries / base / Data / Set.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module : Data.Set
4 -- Copyright : (c) Daan Leijen 2002
5 -- License : BSD-style
6 -- Maintainer : libraries@haskell.org
7 -- Stability : provisional
8 -- Portability : portable
9 --
10 -- An efficient implementation of sets.
11 --
12 -- This module is intended to be imported @qualified@, to avoid name
13 -- clashes with "Prelude" functions. eg.
14 --
15 -- > import Data.Set as Set
16 --
17 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
18 -- trees of /bounded balance/) as described by:
19 --
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>.
23 --
24 -- * J. Nievergelt and E.M. Reingold,
25 -- \"/Binary search trees of bounded balance/\",
26 -- SIAM journal of computing 2(1), March 1973.
27 --
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
32 -- equality.
33 -----------------------------------------------------------------------------
34
35 module Data.Set (
36 -- * Set type
37 Set -- instance Eq,Ord,Show,Read,Data,Typeable
38
39 -- * Operators
40 , (\\)
41
42 -- * Query
43 , null
44 , size
45 , member
46 , isSubsetOf
47 , isProperSubsetOf
48
49 -- * Construction
50 , empty
51 , singleton
52 , insert
53 , delete
54
55 -- * Combine
56 , union, unions
57 , difference
58 , intersection
59
60 -- * Filter
61 , filter
62 , partition
63 , split
64 , splitMember
65
66 -- * Map
67 , map
68 , mapMonotonic
69
70 -- * Fold
71 , fold
72
73 -- * Min\/Max
74 , findMin
75 , findMax
76 , deleteMin
77 , deleteMax
78 , deleteFindMin
79 , deleteFindMax
80
81 -- * Conversion
82
83 -- ** List
84 , elems
85 , toList
86 , fromList
87
88 -- ** Ordered list
89 , toAscList
90 , fromAscList
91 , fromDistinctAscList
92
93 -- * Debugging
94 , showTree
95 , showTreeWith
96 , valid
97
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
112 ) where
113
114 import Prelude hiding (filter,foldr,null,map)
115 import qualified Data.List as List
116 import Data.Monoid (Monoid(..))
117 import Data.Typeable
118
119 {-
120 -- just for testing
121 import QuickCheck
122 import List (nub,sort)
123 import qualified List
124 -}
125
126 #if __GLASGOW_HASKELL__
127 import Text.Read
128 import Data.Generics.Basics
129 import Data.Generics.Instances
130 #endif
131
132 {--------------------------------------------------------------------
133 Operators
134 --------------------------------------------------------------------}
135 infixl 9 \\ --
136
137 -- | /O(n+m)/. See 'difference'.
138 (\\) :: Ord a => Set a -> Set a -> Set a
139 m1 \\ m2 = difference m1 m2
140
141 {--------------------------------------------------------------------
142 Sets are size balanced trees
143 --------------------------------------------------------------------}
144 -- | A set of values @a@.
145 data Set a = Tip
146 | Bin {-# UNPACK #-} !Size a !(Set a) !(Set a)
147
148 type Size = Int
149
150 instance Ord a => Monoid (Set a) where
151 mempty = empty
152 mappend = union
153 mconcat = unions
154
155 #if __GLASGOW_HASKELL__
156
157 {--------------------------------------------------------------------
158 A Data instance
159 --------------------------------------------------------------------}
160
161 -- This instance preserves data abstraction at the cost of inefficiency.
162 -- We omit reflection services for the sake of data abstraction.
163
164 instance (Data a, Ord a) => Data (Set a) where
165 gfoldl f z set = z fromList `f` (toList set)
166 toConstr _ = error "toConstr"
167 gunfold _ _ = error "gunfold"
168 dataTypeOf _ = mkNorepType "Data.Set.Set"
169
170 #endif
171
172 {--------------------------------------------------------------------
173 Query
174 --------------------------------------------------------------------}
175 -- | /O(1)/. Is this the empty set?
176 null :: Set a -> Bool
177 null t
178 = case t of
179 Tip -> True
180 Bin sz x l r -> False
181
182 -- | /O(1)/. The number of elements in the set.
183 size :: Set a -> Int
184 size t
185 = case t of
186 Tip -> 0
187 Bin sz x l r -> sz
188
189 -- | /O(log n)/. Is the element in the set?
190 member :: Ord a => a -> Set a -> Bool
191 member x t
192 = case t of
193 Tip -> False
194 Bin sz y l r
195 -> case compare x y of
196 LT -> member x l
197 GT -> member x r
198 EQ -> True
199
200 {--------------------------------------------------------------------
201 Construction
202 --------------------------------------------------------------------}
203 -- | /O(1)/. The empty set.
204 empty :: Set a
205 empty
206 = Tip
207
208 -- | /O(1)/. Create a singleton set.
209 singleton :: a -> Set a
210 singleton x
211 = Bin 1 x Tip Tip
212
213 {--------------------------------------------------------------------
214 Insertion, Deletion
215 --------------------------------------------------------------------}
216 -- | /O(log n)/. Insert an element in a set.
217 -- If the set already contains an element equal to the given value,
218 -- it is replaced with the new value.
219 insert :: Ord a => a -> Set a -> Set a
220 insert x t
221 = case t of
222 Tip -> singleton x
223 Bin sz y l r
224 -> case compare x y of
225 LT -> balance y (insert x l) r
226 GT -> balance y l (insert x r)
227 EQ -> Bin sz x l r
228
229
230 -- | /O(log n)/. Delete an element from a set.
231 delete :: Ord a => a -> Set a -> Set a
232 delete x t
233 = case t of
234 Tip -> Tip
235 Bin sz y l r
236 -> case compare x y of
237 LT -> balance y (delete x l) r
238 GT -> balance y l (delete x r)
239 EQ -> glue l r
240
241 {--------------------------------------------------------------------
242 Subset
243 --------------------------------------------------------------------}
244 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
245 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
246 isProperSubsetOf s1 s2
247 = (size s1 < size s2) && (isSubsetOf s1 s2)
248
249
250 -- | /O(n+m)/. Is this a subset?
251 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
252 isSubsetOf :: Ord a => Set a -> Set a -> Bool
253 isSubsetOf t1 t2
254 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
255
256 isSubsetOfX Tip t = True
257 isSubsetOfX t Tip = False
258 isSubsetOfX (Bin _ x l r) t
259 = found && isSubsetOfX l lt && isSubsetOfX r gt
260 where
261 (lt,found,gt) = splitMember x t
262
263
264 {--------------------------------------------------------------------
265 Minimal, Maximal
266 --------------------------------------------------------------------}
267 -- | /O(log n)/. The minimal element of a set.
268 findMin :: Set a -> a
269 findMin (Bin _ x Tip r) = x
270 findMin (Bin _ x l r) = findMin l
271 findMin Tip = error "Set.findMin: empty set has no minimal element"
272
273 -- | /O(log n)/. The maximal element of a set.
274 findMax :: Set a -> a
275 findMax (Bin _ x l Tip) = x
276 findMax (Bin _ x l r) = findMax r
277 findMax Tip = error "Set.findMax: empty set has no maximal element"
278
279 -- | /O(log n)/. Delete the minimal element.
280 deleteMin :: Set a -> Set a
281 deleteMin (Bin _ x Tip r) = r
282 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
283 deleteMin Tip = Tip
284
285 -- | /O(log n)/. Delete the maximal element.
286 deleteMax :: Set a -> Set a
287 deleteMax (Bin _ x l Tip) = l
288 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
289 deleteMax Tip = Tip
290
291
292 {--------------------------------------------------------------------
293 Union.
294 --------------------------------------------------------------------}
295 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
296 unions :: Ord a => [Set a] -> Set a
297 unions ts
298 = foldlStrict union empty ts
299
300
301 -- | /O(n+m)/. The union of two sets, preferring the first set when
302 -- equal elements are encountered.
303 -- The implementation uses the efficient /hedge-union/ algorithm.
304 -- Hedge-union is more efficient on (bigset `union` smallset).
305 union :: Ord a => Set a -> Set a -> Set a
306 union Tip t2 = t2
307 union t1 Tip = t1
308 union t1 t2
309 | size t1 >= size t2 = hedgeUnion (const LT) (const GT) t1 t2
310 | otherwise = hedgeUnion (const LT) (const GT) t2 t1
311
312 hedgeUnion cmplo cmphi t1 Tip
313 = t1
314 hedgeUnion cmplo cmphi Tip (Bin _ x l r)
315 = join x (filterGt cmplo l) (filterLt cmphi r)
316 hedgeUnion cmplo cmphi (Bin _ x l r) t2
317 = join x (hedgeUnion cmplo cmpx l (trim cmplo cmpx t2))
318 (hedgeUnion cmpx cmphi r (trim cmpx cmphi t2))
319 where
320 cmpx y = compare x y
321
322 {--------------------------------------------------------------------
323 Difference
324 --------------------------------------------------------------------}
325 -- | /O(n+m)/. Difference of two sets.
326 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
327 difference :: Ord a => Set a -> Set a -> Set a
328 difference Tip t2 = Tip
329 difference t1 Tip = t1
330 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
331
332 hedgeDiff cmplo cmphi Tip t
333 = Tip
334 hedgeDiff cmplo cmphi (Bin _ x l r) Tip
335 = join x (filterGt cmplo l) (filterLt cmphi r)
336 hedgeDiff cmplo cmphi t (Bin _ x l r)
337 = merge (hedgeDiff cmplo cmpx (trim cmplo cmpx t) l)
338 (hedgeDiff cmpx cmphi (trim cmpx cmphi t) r)
339 where
340 cmpx y = compare x y
341
342 {--------------------------------------------------------------------
343 Intersection
344 --------------------------------------------------------------------}
345 -- | /O(n+m)/. The intersection of two sets.
346 -- Intersection is more efficient on (bigset `intersection` smallset).
347 intersection :: Ord a => Set a -> Set a -> Set a
348 intersection Tip t = Tip
349 intersection t Tip = Tip
350 intersection t1 t2
351 | size t1 >= size t2 = intersect' t1 t2
352 | otherwise = intersect' t2 t1
353
354 intersect' Tip t = Tip
355 intersect' t Tip = Tip
356 intersect' t (Bin _ x l r)
357 | found = join x tl tr
358 | otherwise = merge tl tr
359 where
360 (lt,found,gt) = splitMember x t
361 tl = intersect' lt l
362 tr = intersect' gt r
363
364
365 {--------------------------------------------------------------------
366 Filter and partition
367 --------------------------------------------------------------------}
368 -- | /O(n)/. Filter all elements that satisfy the predicate.
369 filter :: Ord a => (a -> Bool) -> Set a -> Set a
370 filter p Tip = Tip
371 filter p (Bin _ x l r)
372 | p x = join x (filter p l) (filter p r)
373 | otherwise = merge (filter p l) (filter p r)
374
375 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
376 -- the predicate and one with all elements that don't satisfy the predicate.
377 -- See also 'split'.
378 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
379 partition p Tip = (Tip,Tip)
380 partition p (Bin _ x l r)
381 | p x = (join x l1 r1,merge l2 r2)
382 | otherwise = (merge l1 r1,join x l2 r2)
383 where
384 (l1,l2) = partition p l
385 (r1,r2) = partition p r
386
387 {----------------------------------------------------------------------
388 Map
389 ----------------------------------------------------------------------}
390
391 -- | /O(n*log n)/.
392 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
393 --
394 -- It's worth noting that the size of the result may be smaller if,
395 -- for some @(x,y)@, @x \/= y && f x == f y@
396
397 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
398 map f = fromList . List.map f . toList
399
400 -- | /O(n)/. The
401 --
402 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
403 -- /The precondition is not checked./
404 -- Semi-formally, we have:
405 --
406 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
407 -- > ==> mapMonotonic f s == map f s
408 -- > where ls = toList s
409
410 mapMonotonic :: (a->b) -> Set a -> Set b
411 mapMonotonic f Tip = Tip
412 mapMonotonic f (Bin sz x l r) =
413 Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
414
415
416 {--------------------------------------------------------------------
417 Fold
418 --------------------------------------------------------------------}
419 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
420 fold :: (a -> b -> b) -> b -> Set a -> b
421 fold f z s
422 = foldr f z s
423
424 -- | /O(n)/. Post-order fold.
425 foldr :: (a -> b -> b) -> b -> Set a -> b
426 foldr f z Tip = z
427 foldr f z (Bin _ x l r) = foldr f (f x (foldr f z r)) l
428
429 {--------------------------------------------------------------------
430 List variations
431 --------------------------------------------------------------------}
432 -- | /O(n)/. The elements of a set.
433 elems :: Set a -> [a]
434 elems s
435 = toList s
436
437 {--------------------------------------------------------------------
438 Lists
439 --------------------------------------------------------------------}
440 -- | /O(n)/. Convert the set to a list of elements.
441 toList :: Set a -> [a]
442 toList s
443 = toAscList s
444
445 -- | /O(n)/. Convert the set to an ascending list of elements.
446 toAscList :: Set a -> [a]
447 toAscList t
448 = foldr (:) [] t
449
450
451 -- | /O(n*log n)/. Create a set from a list of elements.
452 fromList :: Ord a => [a] -> Set a
453 fromList xs
454 = foldlStrict ins empty xs
455 where
456 ins t x = insert x t
457
458 {--------------------------------------------------------------------
459 Building trees from ascending/descending lists can be done in linear time.
460
461 Note that if [xs] is ascending that:
462 fromAscList xs == fromList xs
463 --------------------------------------------------------------------}
464 -- | /O(n)/. Build a set from an ascending list in linear time.
465 -- /The precondition (input list is ascending) is not checked./
466 fromAscList :: Eq a => [a] -> Set a
467 fromAscList xs
468 = fromDistinctAscList (combineEq xs)
469 where
470 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
471 combineEq xs
472 = case xs of
473 [] -> []
474 [x] -> [x]
475 (x:xx) -> combineEq' x xx
476
477 combineEq' z [] = [z]
478 combineEq' z (x:xs)
479 | z==x = combineEq' z xs
480 | otherwise = z:combineEq' x xs
481
482
483 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
484 -- /The precondition (input list is strictly ascending) is not checked./
485 fromDistinctAscList :: [a] -> Set a
486 fromDistinctAscList xs
487 = build const (length xs) xs
488 where
489 -- 1) use continutations so that we use heap space instead of stack space.
490 -- 2) special case for n==5 to build bushier trees.
491 build c 0 xs = c Tip xs
492 build c 5 xs = case xs of
493 (x1:x2:x3:x4:x5:xx)
494 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
495 build c n xs = seq nr $ build (buildR nr c) nl xs
496 where
497 nl = n `div` 2
498 nr = n - nl - 1
499
500 buildR n c l (x:ys) = build (buildB l x c) n ys
501 buildB l x c r zs = c (bin x l r) zs
502
503 {--------------------------------------------------------------------
504 Eq converts the set to a list. In a lazy setting, this
505 actually seems one of the faster methods to compare two trees
506 and it is certainly the simplest :-)
507 --------------------------------------------------------------------}
508 instance Eq a => Eq (Set a) where
509 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
510
511 {--------------------------------------------------------------------
512 Ord
513 --------------------------------------------------------------------}
514
515 instance Ord a => Ord (Set a) where
516 compare s1 s2 = compare (toAscList s1) (toAscList s2)
517
518 {--------------------------------------------------------------------
519 Show
520 --------------------------------------------------------------------}
521 instance Show a => Show (Set a) where
522 showsPrec p xs = showParen (p > 10) $
523 showString "fromList " . shows (toList xs)
524
525 showSet :: (Show a) => [a] -> ShowS
526 showSet []
527 = showString "{}"
528 showSet (x:xs)
529 = showChar '{' . shows x . showTail xs
530 where
531 showTail [] = showChar '}'
532 showTail (x:xs) = showChar ',' . shows x . showTail xs
533
534 {--------------------------------------------------------------------
535 Read
536 --------------------------------------------------------------------}
537 instance (Read a, Ord a) => Read (Set a) where
538 #ifdef __GLASGOW_HASKELL__
539 readPrec = parens $ prec 10 $ do
540 Ident "fromList" <- lexP
541 xs <- readPrec
542 return (fromList xs)
543
544 readListPrec = readListPrecDefault
545 #else
546 readsPrec p = readParen (p > 10) $ \ r -> do
547 ("fromList",s) <- lex r
548 (xs,t) <- reads s
549 return (fromList xs,t)
550 #endif
551
552 {--------------------------------------------------------------------
553 Typeable/Data
554 --------------------------------------------------------------------}
555
556 #include "Typeable.h"
557 INSTANCE_TYPEABLE1(Set,setTc,"Set")
558
559 {--------------------------------------------------------------------
560 Utility functions that return sub-ranges of the original
561 tree. Some functions take a comparison function as argument to
562 allow comparisons against infinite values. A function [cmplo x]
563 should be read as [compare lo x].
564
565 [trim cmplo cmphi t] A tree that is either empty or where [cmplo x == LT]
566 and [cmphi x == GT] for the value [x] of the root.
567 [filterGt cmp t] A tree where for all values [k]. [cmp k == LT]
568 [filterLt cmp t] A tree where for all values [k]. [cmp k == GT]
569
570 [split k t] Returns two trees [l] and [r] where all values
571 in [l] are <[k] and all keys in [r] are >[k].
572 [splitMember k t] Just like [split] but also returns whether [k]
573 was found in the tree.
574 --------------------------------------------------------------------}
575
576 {--------------------------------------------------------------------
577 [trim lo hi t] trims away all subtrees that surely contain no
578 values between the range [lo] to [hi]. The returned tree is either
579 empty or the key of the root is between @lo@ and @hi@.
580 --------------------------------------------------------------------}
581 trim :: (a -> Ordering) -> (a -> Ordering) -> Set a -> Set a
582 trim cmplo cmphi Tip = Tip
583 trim cmplo cmphi t@(Bin sx x l r)
584 = case cmplo x of
585 LT -> case cmphi x of
586 GT -> t
587 le -> trim cmplo cmphi l
588 ge -> trim cmplo cmphi r
589
590 trimMemberLo :: Ord a => a -> (a -> Ordering) -> Set a -> (Bool, Set a)
591 trimMemberLo lo cmphi Tip = (False,Tip)
592 trimMemberLo lo cmphi t@(Bin sx x l r)
593 = case compare lo x of
594 LT -> case cmphi x of
595 GT -> (member lo t, t)
596 le -> trimMemberLo lo cmphi l
597 GT -> trimMemberLo lo cmphi r
598 EQ -> (True,trim (compare lo) cmphi r)
599
600
601 {--------------------------------------------------------------------
602 [filterGt x t] filter all values >[x] from tree [t]
603 [filterLt x t] filter all values <[x] from tree [t]
604 --------------------------------------------------------------------}
605 filterGt :: (a -> Ordering) -> Set a -> Set a
606 filterGt cmp Tip = Tip
607 filterGt cmp (Bin sx x l r)
608 = case cmp x of
609 LT -> join x (filterGt cmp l) r
610 GT -> filterGt cmp r
611 EQ -> r
612
613 filterLt :: (a -> Ordering) -> Set a -> Set a
614 filterLt cmp Tip = Tip
615 filterLt cmp (Bin sx x l r)
616 = case cmp x of
617 LT -> filterLt cmp l
618 GT -> join x l (filterLt cmp r)
619 EQ -> l
620
621
622 {--------------------------------------------------------------------
623 Split
624 --------------------------------------------------------------------}
625 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
626 -- where all elements in @set1@ are lower than @x@ and all elements in
627 -- @set2@ larger than @x@. @x@ is not found in neither @set1@ nor @set2@.
628 split :: Ord a => a -> Set a -> (Set a,Set a)
629 split x Tip = (Tip,Tip)
630 split x (Bin sy y l r)
631 = case compare x y of
632 LT -> let (lt,gt) = split x l in (lt,join y gt r)
633 GT -> let (lt,gt) = split x r in (join y l lt,gt)
634 EQ -> (l,r)
635
636 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
637 -- element was found in the original set.
638 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
639 splitMember x Tip = (Tip,False,Tip)
640 splitMember x (Bin sy y l r)
641 = case compare x y of
642 LT -> let (lt,found,gt) = splitMember x l in (lt,found,join y gt r)
643 GT -> let (lt,found,gt) = splitMember x r in (join y l lt,found,gt)
644 EQ -> (l,True,r)
645
646 {--------------------------------------------------------------------
647 Utility functions that maintain the balance properties of the tree.
648 All constructors assume that all values in [l] < [x] and all values
649 in [r] > [x], and that [l] and [r] are valid trees.
650
651 In order of sophistication:
652 [Bin sz x l r] The type constructor.
653 [bin x l r] Maintains the correct size, assumes that both [l]
654 and [r] are balanced with respect to each other.
655 [balance x l r] Restores the balance and size.
656 Assumes that the original tree was balanced and
657 that [l] or [r] has changed by at most one element.
658 [join x l r] Restores balance and size.
659
660 Furthermore, we can construct a new tree from two trees. Both operations
661 assume that all values in [l] < all values in [r] and that [l] and [r]
662 are valid:
663 [glue l r] Glues [l] and [r] together. Assumes that [l] and
664 [r] are already balanced with respect to each other.
665 [merge l r] Merges two trees and restores balance.
666
667 Note: in contrast to Adam's paper, we use (<=) comparisons instead
668 of (<) comparisons in [join], [merge] and [balance].
669 Quickcheck (on [difference]) showed that this was necessary in order
670 to maintain the invariants. It is quite unsatisfactory that I haven't
671 been able to find out why this is actually the case! Fortunately, it
672 doesn't hurt to be a bit more conservative.
673 --------------------------------------------------------------------}
674
675 {--------------------------------------------------------------------
676 Join
677 --------------------------------------------------------------------}
678 join :: a -> Set a -> Set a -> Set a
679 join x Tip r = insertMin x r
680 join x l Tip = insertMax x l
681 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
682 | delta*sizeL <= sizeR = balance z (join x l lz) rz
683 | delta*sizeR <= sizeL = balance y ly (join x ry r)
684 | otherwise = bin x l r
685
686
687 -- insertMin and insertMax don't perform potentially expensive comparisons.
688 insertMax,insertMin :: a -> Set a -> Set a
689 insertMax x t
690 = case t of
691 Tip -> singleton x
692 Bin sz y l r
693 -> balance y l (insertMax x r)
694
695 insertMin x t
696 = case t of
697 Tip -> singleton x
698 Bin sz y l r
699 -> balance y (insertMin x l) r
700
701 {--------------------------------------------------------------------
702 [merge l r]: merges two trees.
703 --------------------------------------------------------------------}
704 merge :: Set a -> Set a -> Set a
705 merge Tip r = r
706 merge l Tip = l
707 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
708 | delta*sizeL <= sizeR = balance y (merge l ly) ry
709 | delta*sizeR <= sizeL = balance x lx (merge rx r)
710 | otherwise = glue l r
711
712 {--------------------------------------------------------------------
713 [glue l r]: glues two trees together.
714 Assumes that [l] and [r] are already balanced with respect to each other.
715 --------------------------------------------------------------------}
716 glue :: Set a -> Set a -> Set a
717 glue Tip r = r
718 glue l Tip = l
719 glue l r
720 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
721 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
722
723
724 -- | /O(log n)/. Delete and find the minimal element.
725 --
726 -- > deleteFindMin set = (findMin set, deleteMin set)
727
728 deleteFindMin :: Set a -> (a,Set a)
729 deleteFindMin t
730 = case t of
731 Bin _ x Tip r -> (x,r)
732 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
733 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
734
735 -- | /O(log n)/. Delete and find the maximal element.
736 --
737 -- > deleteFindMax set = (findMax set, deleteMax set)
738 deleteFindMax :: Set a -> (a,Set a)
739 deleteFindMax t
740 = case t of
741 Bin _ x l Tip -> (x,l)
742 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
743 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
744
745
746 {--------------------------------------------------------------------
747 [balance x l r] balances two trees with value x.
748 The sizes of the trees should balance after decreasing the
749 size of one of them. (a rotation).
750
751 [delta] is the maximal relative difference between the sizes of
752 two trees, it corresponds with the [w] in Adams' paper,
753 or equivalently, [1/delta] corresponds with the $\alpha$
754 in Nievergelt's paper. Adams shows that [delta] should
755 be larger than 3.745 in order to garantee that the
756 rotations can always restore balance.
757
758 [ratio] is the ratio between an outer and inner sibling of the
759 heavier subtree in an unbalanced setting. It determines
760 whether a double or single rotation should be performed
761 to restore balance. It is correspondes with the inverse
762 of $\alpha$ in Adam's article.
763
764 Note that:
765 - [delta] should be larger than 4.646 with a [ratio] of 2.
766 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
767
768 - A lower [delta] leads to a more 'perfectly' balanced tree.
769 - A higher [delta] performs less rebalancing.
770
771 - Balancing is automatic for random data and a balancing
772 scheme is only necessary to avoid pathological worst cases.
773 Almost any choice will do in practice
774
775 - Allthough it seems that a rather large [delta] may perform better
776 than smaller one, measurements have shown that the smallest [delta]
777 of 4 is actually the fastest on a wide range of operations. It
778 especially improves performance on worst-case scenarios like
779 a sequence of ordered insertions.
780
781 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
782 to decide whether a single or double rotation is needed. Allthough
783 he actually proves that this ratio is needed to maintain the
784 invariants, his implementation uses a (invalid) ratio of 1.
785 He is aware of the problem though since he has put a comment in his
786 original source code that he doesn't care about generating a
787 slightly inbalanced tree since it doesn't seem to matter in practice.
788 However (since we use quickcheck :-) we will stick to strictly balanced
789 trees.
790 --------------------------------------------------------------------}
791 delta,ratio :: Int
792 delta = 4
793 ratio = 2
794
795 balance :: a -> Set a -> Set a -> Set a
796 balance x l r
797 | sizeL + sizeR <= 1 = Bin sizeX x l r
798 | sizeR >= delta*sizeL = rotateL x l r
799 | sizeL >= delta*sizeR = rotateR x l r
800 | otherwise = Bin sizeX x l r
801 where
802 sizeL = size l
803 sizeR = size r
804 sizeX = sizeL + sizeR + 1
805
806 -- rotate
807 rotateL x l r@(Bin _ _ ly ry)
808 | size ly < ratio*size ry = singleL x l r
809 | otherwise = doubleL x l r
810
811 rotateR x l@(Bin _ _ ly ry) r
812 | size ry < ratio*size ly = singleR x l r
813 | otherwise = doubleR x l r
814
815 -- basic rotations
816 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
817 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
818
819 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
820 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
821
822
823 {--------------------------------------------------------------------
824 The bin constructor maintains the size of the tree
825 --------------------------------------------------------------------}
826 bin :: a -> Set a -> Set a -> Set a
827 bin x l r
828 = Bin (size l + size r + 1) x l r
829
830
831 {--------------------------------------------------------------------
832 Utilities
833 --------------------------------------------------------------------}
834 foldlStrict f z xs
835 = case xs of
836 [] -> z
837 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
838
839
840 {--------------------------------------------------------------------
841 Debugging
842 --------------------------------------------------------------------}
843 -- | /O(n)/. Show the tree that implements the set. The tree is shown
844 -- in a compressed, hanging format.
845 showTree :: Show a => Set a -> String
846 showTree s
847 = showTreeWith True False s
848
849
850 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
851 the tree that implements the set. If @hang@ is
852 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
853 @wide@ is 'True', an extra wide version is shown.
854
855 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
856 > 4
857 > +--2
858 > | +--1
859 > | +--3
860 > +--5
861 >
862 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
863 > 4
864 > |
865 > +--2
866 > | |
867 > | +--1
868 > | |
869 > | +--3
870 > |
871 > +--5
872 >
873 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
874 > +--5
875 > |
876 > 4
877 > |
878 > | +--3
879 > | |
880 > +--2
881 > |
882 > +--1
883
884 -}
885 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
886 showTreeWith hang wide t
887 | hang = (showsTreeHang wide [] t) ""
888 | otherwise = (showsTree wide [] [] t) ""
889
890 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
891 showsTree wide lbars rbars t
892 = case t of
893 Tip -> showsBars lbars . showString "|\n"
894 Bin sz x Tip Tip
895 -> showsBars lbars . shows x . showString "\n"
896 Bin sz x l r
897 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
898 showWide wide rbars .
899 showsBars lbars . shows x . showString "\n" .
900 showWide wide lbars .
901 showsTree wide (withEmpty lbars) (withBar lbars) l
902
903 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
904 showsTreeHang wide bars t
905 = case t of
906 Tip -> showsBars bars . showString "|\n"
907 Bin sz x Tip Tip
908 -> showsBars bars . shows x . showString "\n"
909 Bin sz x l r
910 -> showsBars bars . shows x . showString "\n" .
911 showWide wide bars .
912 showsTreeHang wide (withBar bars) l .
913 showWide wide bars .
914 showsTreeHang wide (withEmpty bars) r
915
916
917 showWide wide bars
918 | wide = showString (concat (reverse bars)) . showString "|\n"
919 | otherwise = id
920
921 showsBars :: [String] -> ShowS
922 showsBars bars
923 = case bars of
924 [] -> id
925 _ -> showString (concat (reverse (tail bars))) . showString node
926
927 node = "+--"
928 withBar bars = "| ":bars
929 withEmpty bars = " ":bars
930
931 {--------------------------------------------------------------------
932 Assertions
933 --------------------------------------------------------------------}
934 -- | /O(n)/. Test if the internal set structure is valid.
935 valid :: Ord a => Set a -> Bool
936 valid t
937 = balanced t && ordered t && validsize t
938
939 ordered t
940 = bounded (const True) (const True) t
941 where
942 bounded lo hi t
943 = case t of
944 Tip -> True
945 Bin sz x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
946
947 balanced :: Set a -> Bool
948 balanced t
949 = case t of
950 Tip -> True
951 Bin sz x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
952 balanced l && balanced r
953
954
955 validsize t
956 = (realsize t == Just (size t))
957 where
958 realsize t
959 = case t of
960 Tip -> Just 0
961 Bin sz x l r -> case (realsize l,realsize r) of
962 (Just n,Just m) | n+m+1 == sz -> Just sz
963 other -> Nothing
964
965 {-
966 {--------------------------------------------------------------------
967 Testing
968 --------------------------------------------------------------------}
969 testTree :: [Int] -> Set Int
970 testTree xs = fromList xs
971 test1 = testTree [1..20]
972 test2 = testTree [30,29..10]
973 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
974
975 {--------------------------------------------------------------------
976 QuickCheck
977 --------------------------------------------------------------------}
978 qcheck prop
979 = check config prop
980 where
981 config = Config
982 { configMaxTest = 500
983 , configMaxFail = 5000
984 , configSize = \n -> (div n 2 + 3)
985 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
986 }
987
988
989 {--------------------------------------------------------------------
990 Arbitrary, reasonably balanced trees
991 --------------------------------------------------------------------}
992 instance (Enum a) => Arbitrary (Set a) where
993 arbitrary = sized (arbtree 0 maxkey)
994 where maxkey = 10000
995
996 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
997 arbtree lo hi n
998 | n <= 0 = return Tip
999 | lo >= hi = return Tip
1000 | otherwise = do{ i <- choose (lo,hi)
1001 ; m <- choose (1,30)
1002 ; let (ml,mr) | m==(1::Int)= (1,2)
1003 | m==2 = (2,1)
1004 | m==3 = (1,1)
1005 | otherwise = (2,2)
1006 ; l <- arbtree lo (i-1) (n `div` ml)
1007 ; r <- arbtree (i+1) hi (n `div` mr)
1008 ; return (bin (toEnum i) l r)
1009 }
1010
1011
1012 {--------------------------------------------------------------------
1013 Valid tree's
1014 --------------------------------------------------------------------}
1015 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1016 forValid f
1017 = forAll arbitrary $ \t ->
1018 -- classify (balanced t) "balanced" $
1019 classify (size t == 0) "empty" $
1020 classify (size t > 0 && size t <= 10) "small" $
1021 classify (size t > 10 && size t <= 64) "medium" $
1022 classify (size t > 64) "large" $
1023 balanced t ==> f t
1024
1025 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1026 forValidIntTree f
1027 = forValid f
1028
1029 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1030 forValidUnitTree f
1031 = forValid f
1032
1033
1034 prop_Valid
1035 = forValidUnitTree $ \t -> valid t
1036
1037 {--------------------------------------------------------------------
1038 Single, Insert, Delete
1039 --------------------------------------------------------------------}
1040 prop_Single :: Int -> Bool
1041 prop_Single x
1042 = (insert x empty == singleton x)
1043
1044 prop_InsertValid :: Int -> Property
1045 prop_InsertValid k
1046 = forValidUnitTree $ \t -> valid (insert k t)
1047
1048 prop_InsertDelete :: Int -> Set Int -> Property
1049 prop_InsertDelete k t
1050 = not (member k t) ==> delete k (insert k t) == t
1051
1052 prop_DeleteValid :: Int -> Property
1053 prop_DeleteValid k
1054 = forValidUnitTree $ \t ->
1055 valid (delete k (insert k t))
1056
1057 {--------------------------------------------------------------------
1058 Balance
1059 --------------------------------------------------------------------}
1060 prop_Join :: Int -> Property
1061 prop_Join x
1062 = forValidUnitTree $ \t ->
1063 let (l,r) = split x t
1064 in valid (join x l r)
1065
1066 prop_Merge :: Int -> Property
1067 prop_Merge x
1068 = forValidUnitTree $ \t ->
1069 let (l,r) = split x t
1070 in valid (merge l r)
1071
1072
1073 {--------------------------------------------------------------------
1074 Union
1075 --------------------------------------------------------------------}
1076 prop_UnionValid :: Property
1077 prop_UnionValid
1078 = forValidUnitTree $ \t1 ->
1079 forValidUnitTree $ \t2 ->
1080 valid (union t1 t2)
1081
1082 prop_UnionInsert :: Int -> Set Int -> Bool
1083 prop_UnionInsert x t
1084 = union t (singleton x) == insert x t
1085
1086 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1087 prop_UnionAssoc t1 t2 t3
1088 = union t1 (union t2 t3) == union (union t1 t2) t3
1089
1090 prop_UnionComm :: Set Int -> Set Int -> Bool
1091 prop_UnionComm t1 t2
1092 = (union t1 t2 == union t2 t1)
1093
1094
1095 prop_DiffValid
1096 = forValidUnitTree $ \t1 ->
1097 forValidUnitTree $ \t2 ->
1098 valid (difference t1 t2)
1099
1100 prop_Diff :: [Int] -> [Int] -> Bool
1101 prop_Diff xs ys
1102 = toAscList (difference (fromList xs) (fromList ys))
1103 == List.sort ((List.\\) (nub xs) (nub ys))
1104
1105 prop_IntValid
1106 = forValidUnitTree $ \t1 ->
1107 forValidUnitTree $ \t2 ->
1108 valid (intersection t1 t2)
1109
1110 prop_Int :: [Int] -> [Int] -> Bool
1111 prop_Int xs ys
1112 = toAscList (intersection (fromList xs) (fromList ys))
1113 == List.sort (nub ((List.intersect) (xs) (ys)))
1114
1115 {--------------------------------------------------------------------
1116 Lists
1117 --------------------------------------------------------------------}
1118 prop_Ordered
1119 = forAll (choose (5,100)) $ \n ->
1120 let xs = [0..n::Int]
1121 in fromAscList xs == fromList xs
1122
1123 prop_List :: [Int] -> Bool
1124 prop_List xs
1125 = (sort (nub xs) == toList (fromList xs))
1126 -}
1127
1128 {--------------------------------------------------------------------
1129 Old Data.Set compatibility interface
1130 --------------------------------------------------------------------}
1131
1132 {-# DEPRECATED emptySet "Use empty instead" #-}
1133 -- | Obsolete equivalent of 'empty'.
1134 emptySet :: Set a
1135 emptySet = empty
1136
1137 {-# DEPRECATED mkSet "Use fromList instead" #-}
1138 -- | Obsolete equivalent of 'fromList'.
1139 mkSet :: Ord a => [a] -> Set a
1140 mkSet = fromList
1141
1142 {-# DEPRECATED setToList "Use elems instead." #-}
1143 -- | Obsolete equivalent of 'elems'.
1144 setToList :: Set a -> [a]
1145 setToList = elems
1146
1147 {-# DEPRECATED unitSet "Use singleton instead." #-}
1148 -- | Obsolete equivalent of 'singleton'.
1149 unitSet :: a -> Set a
1150 unitSet = singleton
1151
1152 {-# DEPRECATED elementOf "Use member instead." #-}
1153 -- | Obsolete equivalent of 'member'.
1154 elementOf :: Ord a => a -> Set a -> Bool
1155 elementOf = member
1156
1157 {-# DEPRECATED isEmptySet "Use null instead." #-}
1158 -- | Obsolete equivalent of 'null'.
1159 isEmptySet :: Set a -> Bool
1160 isEmptySet = null
1161
1162 {-# DEPRECATED cardinality "Use size instead." #-}
1163 -- | Obsolete equivalent of 'size'.
1164 cardinality :: Set a -> Int
1165 cardinality = size
1166
1167 {-# DEPRECATED unionManySets "Use unions instead." #-}
1168 -- | Obsolete equivalent of 'unions'.
1169 unionManySets :: Ord a => [Set a] -> Set a
1170 unionManySets = unions
1171
1172 {-# DEPRECATED minusSet "Use difference instead." #-}
1173 -- | Obsolete equivalent of 'difference'.
1174 minusSet :: Ord a => Set a -> Set a -> Set a
1175 minusSet = difference
1176
1177 {-# DEPRECATED mapSet "Use map instead." #-}
1178 -- | Obsolete equivalent of 'map'.
1179 mapSet :: (Ord a, Ord b) => (b -> a) -> Set b -> Set a
1180 mapSet = map
1181
1182 {-# DEPRECATED intersect "Use intersection instead." #-}
1183 -- | Obsolete equivalent of 'intersection'.
1184 intersect :: Ord a => Set a -> Set a -> Set a
1185 intersect = intersection
1186
1187 {-# DEPRECATED addToSet "Use 'flip insert' instead." #-}
1188 -- | Obsolete equivalent of @'flip' 'insert'@.
1189 addToSet :: Ord a => Set a -> a -> Set a
1190 addToSet = flip insert
1191
1192 {-# DEPRECATED delFromSet "Use `flip delete' instead." #-}
1193 -- | Obsolete equivalent of @'flip' 'delete'@.
1194 delFromSet :: Ord a => Set a -> a -> Set a
1195 delFromSet = flip delete