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