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