372e57d345e3851d17e34b3a972f1afb997976b1
[packages/containers.git] / Data / Set.hs
1 {-# OPTIONS -cpp #-}
2 -----------------------------------------------------------------------------
3 -- |
4 -- Module : Data.Set
5 -- Copyright : (c) Daan Leijen 2002
6 -- License : BSD-style
7 -- Maintainer : libraries@haskell.org
8 -- Stability : provisional
9 -- Portability : portable
10 --
11 -- An efficient implementation of sets.
12 --
13 -- Since many function names (but not the type name) clash with
14 -- "Prelude" names, this module is usually imported @qualified@, e.g.
15 --
16 -- > import Data.Set (Set)
17 -- > import qualified Data.Set as Set
18 --
19 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
20 -- trees of /bounded balance/) as described by:
21 --
22 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
23 -- Journal of Functional Programming 3(4):553-562, October 1993,
24 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
25 --
26 -- * J. Nievergelt and E.M. Reingold,
27 -- \"/Binary search trees of bounded balance/\",
28 -- SIAM journal of computing 2(1), March 1973.
29 --
30 -- Note that the implementation is /left-biased/ -- the elements of a
31 -- first argument are always preferred to the second, for example in
32 -- 'union' or 'insert'. Of course, left-biasing can only be observed
33 -- when equality is an equivalence relation instead of structural
34 -- equality.
35 -----------------------------------------------------------------------------
36
37 module Data.Set (
38 -- * Set type
39 #if !defined(TESTING)
40 Set -- instance Eq,Ord,Show,Read,Data,Typeable
41 #else
42 Set(..)
43 #endif
44
45 -- * Operators
46 , (\\)
47
48 -- * Query
49 , null
50 , size
51 , member
52 , notMember
53 , isSubsetOf
54 , isProperSubsetOf
55
56 -- * Construction
57 , empty
58 , singleton
59 , insert
60 , delete
61
62 -- * Combine
63 , union
64 , unions
65 , difference
66 , intersection
67
68 -- * Filter
69 , filter
70 , partition
71 , split
72 , splitMember
73
74 -- * Map
75 , map
76 , mapMonotonic
77
78 -- * Fold
79 , fold
80
81 -- * Min\/Max
82 , findMin
83 , findMax
84 , deleteMin
85 , deleteMax
86 , deleteFindMin
87 , deleteFindMax
88 , maxView
89 , minView
90
91 -- * Conversion
92
93 -- ** List
94 , elems
95 , toList
96 , fromList
97
98 -- ** Ordered list
99 , toAscList
100 , fromAscList
101 , fromDistinctAscList
102
103 -- * Debugging
104 , showTree
105 , showTreeWith
106 , valid
107
108 #if defined(TESTING)
109 -- Internals (for testing)
110 , bin
111 , balanced
112 , join
113 , merge
114 #endif
115 ) where
116
117 import Prelude hiding (filter,foldr,null,map)
118 import qualified Data.List as List
119 import Data.Monoid (Monoid(..))
120 import Data.Foldable (Foldable(foldMap))
121 #ifndef __GLASGOW_HASKELL__
122 import Data.Typeable (Typeable, typeOf, typeOfDefault)
123 #endif
124 import Data.Typeable (Typeable1(..), TyCon, mkTyCon, mkTyConApp)
125
126 {-
127 -- just for testing
128 import QuickCheck
129 import List (nub,sort)
130 import qualified List
131 -}
132
133 #if __GLASGOW_HASKELL__
134 import Text.Read
135 import Data.Data (Data(..), mkNoRepType, gcast1)
136 #endif
137
138 {--------------------------------------------------------------------
139 Operators
140 --------------------------------------------------------------------}
141 infixl 9 \\ --
142
143 -- | /O(n+m)/. See 'difference'.
144 (\\) :: Ord a => Set a -> Set a -> Set a
145 m1 \\ m2 = difference m1 m2
146 {-# INLINE (\\) #-}
147
148 {--------------------------------------------------------------------
149 Sets are size balanced trees
150 --------------------------------------------------------------------}
151 -- | A set of values @a@.
152 data Set a = Tip
153 | Bin {-# UNPACK #-} !Size !a !(Set a) !(Set a)
154
155 type Size = Int
156
157 instance Ord a => Monoid (Set a) where
158 mempty = empty
159 mappend = union
160 mconcat = unions
161
162 instance Foldable Set where
163 foldMap _ Tip = mempty
164 foldMap f (Bin _s k l r) = foldMap f l `mappend` f k `mappend` foldMap f r
165
166 #if __GLASGOW_HASKELL__
167
168 {--------------------------------------------------------------------
169 A Data instance
170 --------------------------------------------------------------------}
171
172 -- This instance preserves data abstraction at the cost of inefficiency.
173 -- We omit reflection services for the sake of data abstraction.
174
175 instance (Data a, Ord a) => Data (Set a) where
176 gfoldl f z set = z fromList `f` (toList set)
177 toConstr _ = error "toConstr"
178 gunfold _ _ = error "gunfold"
179 dataTypeOf _ = mkNoRepType "Data.Set.Set"
180 dataCast1 f = gcast1 f
181
182 #endif
183
184 {--------------------------------------------------------------------
185 Query
186 --------------------------------------------------------------------}
187 -- | /O(1)/. Is this the empty set?
188 null :: Set a -> Bool
189 null Tip = True
190 null (Bin {}) = False
191 {-# INLINE null #-}
192
193 -- | /O(1)/. The number of elements in the set.
194 size :: Set a -> Int
195 size = go
196 where
197 go Tip = 0
198 go (Bin sz _ _ _) = sz
199 {-# INLINE size #-}
200
201 -- | /O(log n)/. Is the element in the set?
202 member :: Ord a => a -> Set a -> Bool
203 member x = x `seq` go
204 where
205 go Tip = False
206 go (Bin _ y l r) = case compare x y of
207 LT -> go l
208 GT -> go r
209 EQ -> True
210 {-# INLINE member #-}
211
212 -- | /O(log n)/. Is the element not in the set?
213 notMember :: Ord a => a -> Set a -> Bool
214 notMember a t = not $ member a t
215 {-# INLINE notMember #-}
216
217 {--------------------------------------------------------------------
218 Construction
219 --------------------------------------------------------------------}
220 -- | /O(1)/. The empty set.
221 empty :: Set a
222 empty = Tip
223 {-# INLINE empty #-}
224
225 -- | /O(1)/. Create a singleton set.
226 singleton :: a -> Set a
227 singleton x = Bin 1 x Tip Tip
228 {-# INLINE singleton #-}
229
230 {--------------------------------------------------------------------
231 Insertion, Deletion
232 --------------------------------------------------------------------}
233 -- | /O(log n)/. Insert an element in a set.
234 -- If the set already contains an element equal to the given value,
235 -- it is replaced with the new value.
236 insert :: Ord a => a -> Set a -> Set a
237 insert x = x `seq` go
238 where
239 go Tip = singleton x
240 go (Bin sz y l r) = case compare x y of
241 LT -> balance y (go l) r
242 GT -> balance y l (go r)
243 EQ -> Bin sz x l r
244 {-# INLINE insert #-}
245
246 -- Insert an element to the set only if it is not in the set. Used by
247 -- `union`.
248 insertR :: Ord a => a -> Set a -> Set a
249 insertR x = x `seq` go
250 where
251 go Tip = singleton x
252 go t@(Bin sz y l r) = case compare x y of
253 LT -> balance y (go l) r
254 GT -> balance y l (go r)
255 EQ -> t
256 {-# INLINE insertR #-}
257
258 -- | /O(log n)/. Delete an element from a set.
259 delete :: Ord a => a -> Set a -> Set a
260 delete x = x `seq` go
261 where
262 go Tip = Tip
263 go (Bin _ y l r) = case compare x y of
264 LT -> balance y (go l) r
265 GT -> balance y l (go r)
266 EQ -> glue l r
267 {-# INLINE delete #-}
268
269 {--------------------------------------------------------------------
270 Subset
271 --------------------------------------------------------------------}
272 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
273 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
274 isProperSubsetOf s1 s2
275 = (size s1 < size s2) && (isSubsetOf s1 s2)
276
277
278 -- | /O(n+m)/. Is this a subset?
279 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
280 isSubsetOf :: Ord a => Set a -> Set a -> Bool
281 isSubsetOf t1 t2
282 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
283
284 isSubsetOfX :: Ord a => Set a -> Set a -> Bool
285 isSubsetOfX Tip _ = True
286 isSubsetOfX _ Tip = False
287 isSubsetOfX (Bin _ x l r) t
288 = found && isSubsetOfX l lt && isSubsetOfX r gt
289 where
290 (lt,found,gt) = splitMember x t
291
292
293 {--------------------------------------------------------------------
294 Minimal, Maximal
295 --------------------------------------------------------------------}
296 -- | /O(log n)/. The minimal element of a set.
297 findMin :: Set a -> a
298 findMin (Bin _ x Tip _) = x
299 findMin (Bin _ _ l _) = findMin l
300 findMin Tip = error "Set.findMin: empty set has no minimal element"
301
302 -- | /O(log n)/. The maximal element of a set.
303 findMax :: Set a -> a
304 findMax (Bin _ x _ Tip) = x
305 findMax (Bin _ _ _ r) = findMax r
306 findMax Tip = error "Set.findMax: empty set has no maximal element"
307
308 -- | /O(log n)/. Delete the minimal element.
309 deleteMin :: Set a -> Set a
310 deleteMin (Bin _ _ Tip r) = r
311 deleteMin (Bin _ x l r) = balance x (deleteMin l) r
312 deleteMin Tip = Tip
313
314 -- | /O(log n)/. Delete the maximal element.
315 deleteMax :: Set a -> Set a
316 deleteMax (Bin _ _ l Tip) = l
317 deleteMax (Bin _ x l r) = balance x l (deleteMax r)
318 deleteMax Tip = Tip
319
320 {--------------------------------------------------------------------
321 Union.
322 --------------------------------------------------------------------}
323 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
324 unions :: Ord a => [Set a] -> Set a
325 unions = foldlStrict union empty
326 {-# INLINE unions #-}
327
328 -- | /O(n+m)/. The union of two sets, preferring the first set when
329 -- equal elements are encountered.
330 -- The implementation uses the efficient /hedge-union/ algorithm.
331 -- Hedge-union is more efficient on (bigset `union` smallset).
332 union :: Ord a => Set a -> Set a -> Set a
333 union Tip t2 = t2
334 union t1 Tip = t1
335 union (Bin _ x Tip Tip) t = insert x t
336 union t (Bin _ x Tip Tip) = insertR x t
337 union t1 t2 = hedgeUnion NothingS NothingS t1 t2
338 {-# INLINE union #-}
339
340 hedgeUnion :: Ord a
341 => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
342 hedgeUnion _ _ t1 Tip
343 = t1
344 hedgeUnion blo bhi Tip (Bin _ x l r)
345 = join x (filterGt blo l) (filterLt bhi r)
346 hedgeUnion blo bhi (Bin _ x l r) t2
347 = join x (hedgeUnion blo bmi l (trim blo bmi t2))
348 (hedgeUnion bmi bhi r (trim bmi bhi t2))
349 where
350 bmi = JustS x
351
352 {--------------------------------------------------------------------
353 Difference
354 --------------------------------------------------------------------}
355 -- | /O(n+m)/. Difference of two sets.
356 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
357 difference :: Ord a => Set a -> Set a -> Set a
358 difference Tip _ = Tip
359 difference t1 Tip = t1
360 difference t1 t2 = hedgeDiff NothingS NothingS t1 t2
361 {-# INLINE difference #-}
362
363 hedgeDiff :: Ord a
364 => MaybeS a -> MaybeS a -> Set a -> Set a -> Set a
365 hedgeDiff _ _ Tip _
366 = Tip
367 hedgeDiff blo bhi (Bin _ x l r) Tip
368 = join x (filterGt blo l) (filterLt bhi r)
369 hedgeDiff blo bhi t (Bin _ x l r)
370 = merge (hedgeDiff blo bmi (trim blo bmi t) l)
371 (hedgeDiff bmi bhi (trim bmi bhi t) r)
372 where
373 bmi = JustS x
374
375 {--------------------------------------------------------------------
376 Intersection
377 --------------------------------------------------------------------}
378 -- | /O(n+m)/. The intersection of two sets.
379 -- Elements of the result come from the first set, so for example
380 --
381 -- > import qualified Data.Set as S
382 -- > data AB = A | B deriving Show
383 -- > instance Ord AB where compare _ _ = EQ
384 -- > instance Eq AB where _ == _ = True
385 -- > main = print (S.singleton A `S.intersection` S.singleton B,
386 -- > S.singleton B `S.intersection` S.singleton A)
387 --
388 -- prints @(fromList [A],fromList [B])@.
389 intersection :: Ord a => Set a -> Set a -> Set a
390 intersection Tip _ = Tip
391 intersection _ Tip = Tip
392 intersection t1@(Bin s1 x1 l1 r1) t2@(Bin s2 x2 l2 r2) =
393 if s1 >= s2 then
394 let (lt,found,gt) = splitLookup x2 t1
395 tl = intersection lt l2
396 tr = intersection gt r2
397 in case found of
398 Just x -> join x tl tr
399 Nothing -> merge tl tr
400 else let (lt,found,gt) = splitMember x1 t2
401 tl = intersection l1 lt
402 tr = intersection r1 gt
403 in if found then join x1 tl tr
404 else merge tl tr
405
406 {--------------------------------------------------------------------
407 Filter and partition
408 --------------------------------------------------------------------}
409 -- | /O(n)/. Filter all elements that satisfy the predicate.
410 filter :: Ord a => (a -> Bool) -> Set a -> Set a
411 filter p = go
412 where
413 go Tip = Tip
414 go (Bin _ x l r)
415 | p x = join x (go l) (go r)
416 | otherwise = merge (go l) (go r)
417 {-# INLINE filter #-}
418
419 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
420 -- the predicate and one with all elements that don't satisfy the predicate.
421 -- See also 'split'.
422 partition :: Ord a => (a -> Bool) -> Set a -> (Set a,Set a)
423 partition p = go
424 where
425 go Tip = (Tip, Tip)
426 go (Bin _ x l r) = case (go l, go r) of
427 ((l1, l2), (r1, r2))
428 | p x -> (join x l1 r1, merge l2 r2)
429 | otherwise -> (merge l1 r1, join x l2 r2)
430 {-# INLINE partition #-}
431
432 {----------------------------------------------------------------------
433 Map
434 ----------------------------------------------------------------------}
435
436 -- | /O(n*log n)/.
437 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
438 --
439 -- It's worth noting that the size of the result may be smaller if,
440 -- for some @(x,y)@, @x \/= y && f x == f y@
441
442 map :: (Ord a, Ord b) => (a->b) -> Set a -> Set b
443 map f = fromList . List.map f . toList
444 {-# INLINE map #-}
445
446 -- | /O(n)/. The
447 --
448 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is monotonic.
449 -- /The precondition is not checked./
450 -- Semi-formally, we have:
451 --
452 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
453 -- > ==> mapMonotonic f s == map f s
454 -- > where ls = toList s
455
456 mapMonotonic :: (a->b) -> Set a -> Set b
457 mapMonotonic f = go
458 where
459 go Tip = Tip
460 go (Bin sz x l r) = Bin sz (f x) (go l) (go r)
461 {-# INLINE mapMonotonic #-}
462
463 {--------------------------------------------------------------------
464 Fold
465 --------------------------------------------------------------------}
466 -- | /O(n)/. Fold over the elements of a set in an unspecified order.
467 fold :: (a -> b -> b) -> b -> Set a -> b
468 fold = foldr
469 {-# INLINE fold #-}
470
471 -- | /O(n)/. Post-order fold.
472 foldr :: (a -> b -> b) -> b -> Set a -> b
473 foldr f = go
474 where
475 go z Tip = z
476 go z (Bin _ x l r) = go (f x (go z r)) l
477 {-# INLINE foldr #-}
478
479 {--------------------------------------------------------------------
480 List variations
481 --------------------------------------------------------------------}
482 -- | /O(n)/. The elements of a set.
483 elems :: Set a -> [a]
484 elems = toList
485 {-# INLINE elems #-}
486
487 {--------------------------------------------------------------------
488 Lists
489 --------------------------------------------------------------------}
490 -- | /O(n)/. Convert the set to a list of elements.
491 toList :: Set a -> [a]
492 toList = toAscList
493 {-# INLINE toList #-}
494
495 -- | /O(n)/. Convert the set to an ascending list of elements.
496 toAscList :: Set a -> [a]
497 toAscList = foldr (:) []
498 {-# INLINE toAscList #-}
499
500 -- | /O(n*log n)/. Create a set from a list of elements.
501 fromList :: Ord a => [a] -> Set a
502 fromList = foldlStrict ins empty
503 where
504 ins t x = insert x t
505 {-# INLINE fromList #-}
506
507 {--------------------------------------------------------------------
508 Building trees from ascending/descending lists can be done in linear time.
509
510 Note that if [xs] is ascending that:
511 fromAscList xs == fromList xs
512 --------------------------------------------------------------------}
513 -- | /O(n)/. Build a set from an ascending list in linear time.
514 -- /The precondition (input list is ascending) is not checked./
515 fromAscList :: Eq a => [a] -> Set a
516 fromAscList xs
517 = fromDistinctAscList (combineEq xs)
518 where
519 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
520 combineEq xs'
521 = case xs' of
522 [] -> []
523 [x] -> [x]
524 (x:xx) -> combineEq' x xx
525
526 combineEq' z [] = [z]
527 combineEq' z (x:xs')
528 | z==x = combineEq' z xs'
529 | otherwise = z:combineEq' x xs'
530
531
532 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
533 -- /The precondition (input list is strictly ascending) is not checked./
534 fromDistinctAscList :: [a] -> Set a
535 fromDistinctAscList xs
536 = build const (length xs) xs
537 where
538 -- 1) use continutations so that we use heap space instead of stack space.
539 -- 2) special case for n==5 to build bushier trees.
540 build c 0 xs' = c Tip xs'
541 build c 5 xs' = case xs' of
542 (x1:x2:x3:x4:x5:xx)
543 -> c (bin x4 (bin x2 (singleton x1) (singleton x3)) (singleton x5)) xx
544 _ -> error "fromDistinctAscList build 5"
545 build c n xs' = seq nr $ build (buildR nr c) nl xs'
546 where
547 nl = n `div` 2
548 nr = n - nl - 1
549
550 buildR n c l (x:ys) = build (buildB l x c) n ys
551 buildR _ _ _ [] = error "fromDistinctAscList buildR []"
552 buildB l x c r zs = c (bin x l r) zs
553
554 {--------------------------------------------------------------------
555 Eq converts the set to a list. In a lazy setting, this
556 actually seems one of the faster methods to compare two trees
557 and it is certainly the simplest :-)
558 --------------------------------------------------------------------}
559 instance Eq a => Eq (Set a) where
560 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
561
562 {--------------------------------------------------------------------
563 Ord
564 --------------------------------------------------------------------}
565
566 instance Ord a => Ord (Set a) where
567 compare s1 s2 = compare (toAscList s1) (toAscList s2)
568
569 {--------------------------------------------------------------------
570 Show
571 --------------------------------------------------------------------}
572 instance Show a => Show (Set a) where
573 showsPrec p xs = showParen (p > 10) $
574 showString "fromList " . shows (toList xs)
575
576 {--------------------------------------------------------------------
577 Read
578 --------------------------------------------------------------------}
579 instance (Read a, Ord a) => Read (Set a) where
580 #ifdef __GLASGOW_HASKELL__
581 readPrec = parens $ prec 10 $ do
582 Ident "fromList" <- lexP
583 xs <- readPrec
584 return (fromList xs)
585
586 readListPrec = readListPrecDefault
587 #else
588 readsPrec p = readParen (p > 10) $ \ r -> do
589 ("fromList",s) <- lex r
590 (xs,t) <- reads s
591 return (fromList xs,t)
592 #endif
593
594 {--------------------------------------------------------------------
595 Typeable/Data
596 --------------------------------------------------------------------}
597
598 #include "Typeable.h"
599 INSTANCE_TYPEABLE1(Set,setTc,"Set")
600
601 {--------------------------------------------------------------------
602 Utility functions that return sub-ranges of the original
603 tree. Some functions take a `Maybe value` as an argument to
604 allow comparisons against infinite values. These are called `blow`
605 (Nothing is -\infty) and `bhigh` (here Nothing is +\infty).
606 We use MaybeS value, which is a Maybe strict in the Just case.
607
608 [trim blow bhigh t] A tree that is either empty or where [x > blow]
609 and [x < bhigh] for the value [x] of the root.
610 [filterGt blow t] A tree where for all values [k]. [k > blow]
611 [filterLt bhigh t] A tree where for all values [k]. [k < bhigh]
612
613 [split k t] Returns two trees [l] and [r] where all values
614 in [l] are <[k] and all keys in [r] are >[k].
615 [splitMember k t] Just like [split] but also returns whether [k]
616 was found in the tree.
617 --------------------------------------------------------------------}
618
619 data MaybeS a = NothingS | JustS !a
620
621 {--------------------------------------------------------------------
622 [trim blo bhi t] trims away all subtrees that surely contain no
623 values between the range [blo] to [bhi]. The returned tree is either
624 empty or the key of the root is between @blo@ and @bhi@.
625 --------------------------------------------------------------------}
626 trim :: Ord a => MaybeS a -> MaybeS a -> Set a -> Set a
627 trim NothingS NothingS t = t
628 trim (JustS lx) NothingS t = greater t where greater (Bin _ x _ r) | x <= lx = greater r
629 greater t = t
630 trim NothingS (JustS hx) t = lesser t where lesser (Bin _ x l _) | x >= hx = lesser l
631 lesser t = t
632 trim (JustS lx) (JustS hx) t = middle t where middle (Bin _ x _ r) | x <= lx = middle r
633 middle (Bin _ x l _) | x >= hx = middle l
634 middle t = t
635
636 {--------------------------------------------------------------------
637 [filterGt b t] filter all values >[b] from tree [t]
638 [filterLt b t] filter all values <[b] from tree [t]
639 --------------------------------------------------------------------}
640 filterGt :: Ord a => MaybeS a -> Set a -> Set a
641 filterGt NothingS t = t
642 filterGt (JustS b) t = filter' t
643 where filter' Tip = Tip
644 filter' (Bin _ x l r) = case compare b x of LT -> join x (filter' l) r
645 EQ -> r
646 GT -> filter' r
647 {-# INLINE filterGt #-}
648
649 filterLt :: Ord a => MaybeS a -> Set a -> Set a
650 filterLt NothingS t = t
651 filterLt (JustS b) t = filter' t
652 where filter' Tip = Tip
653 filter' (Bin _ x l r) = case compare x b of LT -> join x l (filter' r)
654 EQ -> l
655 GT -> filter' l
656 {-# INLINE filterLt #-}
657
658 {--------------------------------------------------------------------
659 Split
660 --------------------------------------------------------------------}
661 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
662 -- where @set1@ comprises the elements of @set@ less than @x@ and @set2@
663 -- comprises the elements of @set@ greater than @x@.
664 split :: Ord a => a -> Set a -> (Set a,Set a)
665 split _ Tip = (Tip,Tip)
666 split x (Bin _ y l r)
667 = case compare x y of
668 LT -> let (lt,gt) = split x l in (lt,join y gt r)
669 GT -> let (lt,gt) = split x r in (join y l lt,gt)
670 EQ -> (l,r)
671
672 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
673 -- element was found in the original set.
674 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
675 splitMember x t = let (l,m,r) = splitLookup x t in
676 (l,maybe False (const True) m,r)
677
678 -- | /O(log n)/. Performs a 'split' but also returns the pivot
679 -- element that was found in the original set.
680 splitLookup :: Ord a => a -> Set a -> (Set a,Maybe a,Set a)
681 splitLookup _ Tip = (Tip,Nothing,Tip)
682 splitLookup x (Bin _ y l r)
683 = case compare x y of
684 LT -> let (lt,found,gt) = splitLookup x l in (lt,found,join y gt r)
685 GT -> let (lt,found,gt) = splitLookup x r in (join y l lt,found,gt)
686 EQ -> (l,Just y,r)
687
688 {--------------------------------------------------------------------
689 Utility functions that maintain the balance properties of the tree.
690 All constructors assume that all values in [l] < [x] and all values
691 in [r] > [x], and that [l] and [r] are valid trees.
692
693 In order of sophistication:
694 [Bin sz x l r] The type constructor.
695 [bin x l r] Maintains the correct size, assumes that both [l]
696 and [r] are balanced with respect to each other.
697 [balance x l r] Restores the balance and size.
698 Assumes that the original tree was balanced and
699 that [l] or [r] has changed by at most one element.
700 [join x l r] Restores balance and size.
701
702 Furthermore, we can construct a new tree from two trees. Both operations
703 assume that all values in [l] < all values in [r] and that [l] and [r]
704 are valid:
705 [glue l r] Glues [l] and [r] together. Assumes that [l] and
706 [r] are already balanced with respect to each other.
707 [merge l r] Merges two trees and restores balance.
708
709 Note: in contrast to Adam's paper, we use (<=) comparisons instead
710 of (<) comparisons in [join], [merge] and [balance].
711 Quickcheck (on [difference]) showed that this was necessary in order
712 to maintain the invariants. It is quite unsatisfactory that I haven't
713 been able to find out why this is actually the case! Fortunately, it
714 doesn't hurt to be a bit more conservative.
715 --------------------------------------------------------------------}
716
717 {--------------------------------------------------------------------
718 Join
719 --------------------------------------------------------------------}
720 join :: a -> Set a -> Set a -> Set a
721 join x Tip r = insertMin x r
722 join x l Tip = insertMax x l
723 join x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
724 | delta*sizeL <= sizeR = balance z (join x l lz) rz
725 | delta*sizeR <= sizeL = balance y ly (join x ry r)
726 | otherwise = bin x l r
727
728
729 -- insertMin and insertMax don't perform potentially expensive comparisons.
730 insertMax,insertMin :: a -> Set a -> Set a
731 insertMax x t
732 = case t of
733 Tip -> singleton x
734 Bin _ y l r
735 -> balance y l (insertMax x r)
736
737 insertMin x t
738 = case t of
739 Tip -> singleton x
740 Bin _ y l r
741 -> balance y (insertMin x l) r
742
743 {--------------------------------------------------------------------
744 [merge l r]: merges two trees.
745 --------------------------------------------------------------------}
746 merge :: Set a -> Set a -> Set a
747 merge Tip r = r
748 merge l Tip = l
749 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
750 | delta*sizeL <= sizeR = balance y (merge l ly) ry
751 | delta*sizeR <= sizeL = balance x lx (merge rx r)
752 | otherwise = glue l r
753
754 {--------------------------------------------------------------------
755 [glue l r]: glues two trees together.
756 Assumes that [l] and [r] are already balanced with respect to each other.
757 --------------------------------------------------------------------}
758 glue :: Set a -> Set a -> Set a
759 glue Tip r = r
760 glue l Tip = l
761 glue l r
762 | size l > size r = let (m,l') = deleteFindMax l in balance m l' r
763 | otherwise = let (m,r') = deleteFindMin r in balance m l r'
764
765
766 -- | /O(log n)/. Delete and find the minimal element.
767 --
768 -- > deleteFindMin set = (findMin set, deleteMin set)
769
770 deleteFindMin :: Set a -> (a,Set a)
771 deleteFindMin t
772 = case t of
773 Bin _ x Tip r -> (x,r)
774 Bin _ x l r -> let (xm,l') = deleteFindMin l in (xm,balance x l' r)
775 Tip -> (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
776
777 -- | /O(log n)/. Delete and find the maximal element.
778 --
779 -- > deleteFindMax set = (findMax set, deleteMax set)
780 deleteFindMax :: Set a -> (a,Set a)
781 deleteFindMax t
782 = case t of
783 Bin _ x l Tip -> (x,l)
784 Bin _ x l r -> let (xm,r') = deleteFindMax r in (xm,balance x l r')
785 Tip -> (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
786
787 -- | /O(log n)/. Retrieves the minimal key of the set, and the set
788 -- stripped of that element, or 'Nothing' if passed an empty set.
789 minView :: Set a -> Maybe (a, Set a)
790 minView Tip = Nothing
791 minView x = Just (deleteFindMin x)
792
793 -- | /O(log n)/. Retrieves the maximal key of the set, and the set
794 -- stripped of that element, or 'Nothing' if passed an empty set.
795 maxView :: Set a -> Maybe (a, Set a)
796 maxView Tip = Nothing
797 maxView x = Just (deleteFindMax x)
798
799 {--------------------------------------------------------------------
800 [balance x l r] balances two trees with value x.
801 The sizes of the trees should balance after decreasing the
802 size of one of them. (a rotation).
803
804 [delta] is the maximal relative difference between the sizes of
805 two trees, it corresponds with the [w] in Adams' paper.
806 [ratio] is the ratio between an outer and inner sibling of the
807 heavier subtree in an unbalanced setting. It determines
808 whether a double or single rotation should be performed
809 to restore balance. It is correspondes with the inverse
810 of $\alpha$ in Adam's article.
811
812 Note that according to the Adam's paper:
813 - [delta] should be larger than 4.646 with a [ratio] of 2.
814 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
815
816 But the Adam's paper is errorneous:
817 - it can be proved that for delta=2 and delta>=5 there does
818 not exist any ratio that would work
819 - delta=4.5 and ratio=2 does not work
820
821 That leaves two reasonable variants, delta=3 and delta=4,
822 both with ratio=2.
823
824 - A lower [delta] leads to a more 'perfectly' balanced tree.
825 - A higher [delta] performs less rebalancing.
826
827 In the benchmarks, delta=3 is faster on insert operations,
828 but delta=4 has better overall performance, so we use delta=4.
829
830 Note: in contrast to Adam's paper, we perform the rebalance
831 even in the case when (size left == delta * size right), instead
832 when (size left > delta * size) as in the paper. Both are correct,
833 but the former is slightly faster overall.
834
835 --------------------------------------------------------------------}
836 delta,ratio :: Int
837 delta = 4
838 ratio = 2
839
840 -- The balance function is equivalent to the following:
841 --
842 -- balance :: a -> Set a -> Set a -> Set a
843 -- balance x l r
844 -- | sizeL + sizeR <= 1 = Bin sizeX x l r
845 -- | sizeR >= delta*sizeL = rotateL x l r
846 -- | sizeL >= delta*sizeR = rotateR x l r
847 -- | otherwise = Bin sizeX x l r
848 -- where
849 -- sizeL = size l
850 -- sizeR = size r
851 -- sizeX = sizeL + sizeR + 1
852 --
853 -- rotateL :: a -> Set a -> Set a -> Set a
854 -- rotateL x l r@(Bin _ _ ly ry) | size ly < ratio*size ry = singleL x l r
855 -- | otherwise = doubleL x l r
856 -- rotateR :: a -> Set a -> Set a -> Set a
857 -- rotateR x l@(Bin _ _ ly ry) r | size ry < ratio*size ly = singleR x l r
858 -- | otherwise = doubleR x l r
859 --
860 -- singleL, singleR :: a -> Set a -> Set a -> Set a
861 -- singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
862 -- singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
863 --
864 -- doubleL, doubleR :: a -> Set a -> Set a -> Set a
865 -- doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
866 -- doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
867 --
868 -- It is only written in such a way that every node is pattern-matched only once.
869
870 balance :: a -> Set a -> Set a -> Set a
871 balance x l r = case l of
872 Tip -> case r of
873 Tip -> Bin 1 x Tip Tip
874 r@(Bin rs rx Tip Tip) -> Bin 2 x Tip r
875 r@(Bin rs rx Tip rr@(Bin _ _ _ _)) -> Bin 3 rx (Bin 1 x Tip Tip) rr
876 r@(Bin rs rx rl@(Bin _ rlx _ _) Tip) -> Bin 3 rlx (Bin 1 x Tip Tip) (Bin 1 rx Tip Tip)
877 r@(Bin rs rx rl@(Bin rls rlx rll rlr) rr@(Bin rrs rrx rrl rrr))
878 | rls < ratio*rrs -> Bin (1+rs) rx (Bin (1+rls) x Tip rl) rr
879 | otherwise -> Bin (1+rs) rlx (Bin (1+size rll) x Tip rll) (Bin (1+rrs+size rlr) rx rlr rr)
880
881 l@(Bin ls lx ll lr) -> case r of
882 Tip -> case (ll, lr) of
883 (Tip, Tip) -> Bin 2 x l Tip
884 (Tip, lr@(Bin _ lrx _ _)) -> Bin 3 lrx (Bin 1 lx Tip Tip) (Bin 1 x Tip Tip)
885 (ll@(Bin _ _ _ _), Tip) -> Bin 3 lx ll (Bin 1 x Tip Tip)
886 (ll@(Bin lls llx lll llr), lr@(Bin lrs lrx lrl lrr))
887 | lrs < ratio*lls -> Bin (1+ls) lx ll (Bin (1+lrs) x lr Tip)
888 | otherwise -> Bin (1+ls) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+size lrr) x lrr Tip)
889 r@(Bin rs rx rl rr)
890 | rs >= delta*ls -> case (rl, rr) of
891 (Bin rls rlx rll rlr, Bin rrs rrx rrl rrr)
892 | rls < ratio*rrs -> Bin (1+ls+rs) rx (Bin (1+ls+rls) x l rl) rr
893 | otherwise -> Bin (1+ls+rs) rlx (Bin (1+ls+size rll) x l rll) (Bin (1+rrs+size rlr) rx rlr rr)
894 | ls >= delta*rs -> case (ll, lr) of
895 (Bin lls llx lll llr, Bin lrs lrx lrl lrr)
896 | lrs < ratio*lls -> Bin (1+ls+rs) lx ll (Bin (1+rs+lrs) x lr r)
897 | otherwise -> Bin (1+ls+rs) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+rs+size lrr) x lrr r)
898 | otherwise -> Bin (1+ls+rs) x l r
899
900
901 {--------------------------------------------------------------------
902 The bin constructor maintains the size of the tree
903 --------------------------------------------------------------------}
904 bin :: a -> Set a -> Set a -> Set a
905 bin x l r
906 = Bin (size l + size r + 1) x l r
907
908
909 {--------------------------------------------------------------------
910 Utilities
911 --------------------------------------------------------------------}
912 foldlStrict :: (a -> b -> a) -> a -> [b] -> a
913 foldlStrict f = go
914 where
915 go z [] = z
916 go z (x:xs) = z `seq` go (f z x) xs
917 {-# INLINE foldlStrict #-}
918
919 {--------------------------------------------------------------------
920 Debugging
921 --------------------------------------------------------------------}
922 -- | /O(n)/. Show the tree that implements the set. The tree is shown
923 -- in a compressed, hanging format.
924 showTree :: Show a => Set a -> String
925 showTree s
926 = showTreeWith True False s
927
928
929 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
930 the tree that implements the set. If @hang@ is
931 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
932 @wide@ is 'True', an extra wide version is shown.
933
934 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
935 > 4
936 > +--2
937 > | +--1
938 > | +--3
939 > +--5
940 >
941 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
942 > 4
943 > |
944 > +--2
945 > | |
946 > | +--1
947 > | |
948 > | +--3
949 > |
950 > +--5
951 >
952 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
953 > +--5
954 > |
955 > 4
956 > |
957 > | +--3
958 > | |
959 > +--2
960 > |
961 > +--1
962
963 -}
964 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
965 showTreeWith hang wide t
966 | hang = (showsTreeHang wide [] t) ""
967 | otherwise = (showsTree wide [] [] t) ""
968
969 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
970 showsTree wide lbars rbars t
971 = case t of
972 Tip -> showsBars lbars . showString "|\n"
973 Bin _ x Tip Tip
974 -> showsBars lbars . shows x . showString "\n"
975 Bin _ x l r
976 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
977 showWide wide rbars .
978 showsBars lbars . shows x . showString "\n" .
979 showWide wide lbars .
980 showsTree wide (withEmpty lbars) (withBar lbars) l
981
982 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
983 showsTreeHang wide bars t
984 = case t of
985 Tip -> showsBars bars . showString "|\n"
986 Bin _ x Tip Tip
987 -> showsBars bars . shows x . showString "\n"
988 Bin _ x l r
989 -> showsBars bars . shows x . showString "\n" .
990 showWide wide bars .
991 showsTreeHang wide (withBar bars) l .
992 showWide wide bars .
993 showsTreeHang wide (withEmpty bars) r
994
995 showWide :: Bool -> [String] -> String -> String
996 showWide wide bars
997 | wide = showString (concat (reverse bars)) . showString "|\n"
998 | otherwise = id
999
1000 showsBars :: [String] -> ShowS
1001 showsBars bars
1002 = case bars of
1003 [] -> id
1004 _ -> showString (concat (reverse (tail bars))) . showString node
1005
1006 node :: String
1007 node = "+--"
1008
1009 withBar, withEmpty :: [String] -> [String]
1010 withBar bars = "| ":bars
1011 withEmpty bars = " ":bars
1012
1013 {--------------------------------------------------------------------
1014 Assertions
1015 --------------------------------------------------------------------}
1016 -- | /O(n)/. Test if the internal set structure is valid.
1017 valid :: Ord a => Set a -> Bool
1018 valid t
1019 = balanced t && ordered t && validsize t
1020
1021 ordered :: Ord a => Set a -> Bool
1022 ordered t
1023 = bounded (const True) (const True) t
1024 where
1025 bounded lo hi t'
1026 = case t' of
1027 Tip -> True
1028 Bin _ x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
1029
1030 balanced :: Set a -> Bool
1031 balanced t
1032 = case t of
1033 Tip -> True
1034 Bin _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1035 balanced l && balanced r
1036
1037 validsize :: Set a -> Bool
1038 validsize t
1039 = (realsize t == Just (size t))
1040 where
1041 realsize t'
1042 = case t' of
1043 Tip -> Just 0
1044 Bin sz _ l r -> case (realsize l,realsize r) of
1045 (Just n,Just m) | n+m+1 == sz -> Just sz
1046 _ -> Nothing