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