O(n) fromAscList IntSet / IntMap
[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 Set -- instance Eq,Ord,Show,Read,Data,Typeable
40
41 -- * Operators
42 , (\\)
43
44 -- * Query
45 , null
46 , size
47 , member
48 , notMember
49 , isSubsetOf
50 , isProperSubsetOf
51
52 -- * Construction
53 , empty
54 , singleton
55 , insert
56 , delete
57
58 -- * Combine
59 , union, unions
60 , difference
61 , intersection
62
63 -- * Filter
64 , filter
65 , partition
66 , split
67 , splitMember
68
69 -- * Map
70 , map
71 , mapMonotonic
72
73 -- * Fold
74 , fold
75
76 -- * Min\/Max
77 , findMin
78 , findMax
79 , deleteMin
80 , deleteMax
81 , deleteFindMin
82 , deleteFindMax
83 , maxView
84 , minView
85
86 -- * Conversion
87
88 -- ** List
89 , elems
90 , toList
91 , fromList
92
93 -- ** Ordered list
94 , toAscList
95 , fromAscList
96 , fromDistinctAscList
97
98 -- * Debugging
99 , showTree
100 , showTreeWith
101 , valid
102 ) where
103
104 import Prelude hiding (filter,foldr,null,map)
105 import qualified Data.List as List
106 import Data.Monoid (Monoid(..))
107 import Data.Foldable (Foldable(foldMap))
108 #ifndef __GLASGOW_HASKELL__
109 import Data.Typeable (Typeable, typeOf, typeOfDefault)
110 #endif
111 import Data.Typeable (Typeable1(..), TyCon, mkTyCon, mkTyConApp)
112
113 {-
114 -- just for testing
115 import QuickCheck
116 import List (nub,sort)
117 import qualified List
118 -}
119
120 #if __GLASGOW_HASKELL__
121 import Text.Read
122 import Data.Data (Data(..), mkNoRepType, gcast1)
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
774 -- stripped of that element, or 'Nothing' if passed an empty set.
775 minView :: Set a -> Maybe (a, Set a)
776 minView Tip = Nothing
777 minView x = Just (deleteFindMin x)
778
779 -- | /O(log n)/. Retrieves the maximal key of the set, and the set
780 -- stripped of that element, or 'Nothing' if passed an empty set.
781 maxView :: Set a -> Maybe (a, Set a)
782 maxView Tip = Nothing
783 maxView x = Just (deleteFindMax x)
784
785 {--------------------------------------------------------------------
786 [balance x l r] balances two trees with value x.
787 The sizes of the trees should balance after decreasing the
788 size of one of them. (a rotation).
789
790 [delta] is the maximal relative difference between the sizes of
791 two trees, it corresponds with the [w] in Adams' paper,
792 or equivalently, [1/delta] corresponds with the $\alpha$
793 in Nievergelt's paper. Adams shows that [delta] should
794 be larger than 3.745 in order to garantee that the
795 rotations can always restore balance.
796
797 [ratio] is the ratio between an outer and inner sibling of the
798 heavier subtree in an unbalanced setting. It determines
799 whether a double or single rotation should be performed
800 to restore balance. It is correspondes with the inverse
801 of $\alpha$ in Adam's article.
802
803 Note that:
804 - [delta] should be larger than 4.646 with a [ratio] of 2.
805 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
806
807 - A lower [delta] leads to a more 'perfectly' balanced tree.
808 - A higher [delta] performs less rebalancing.
809
810 - Balancing is automatic for random data and a balancing
811 scheme is only necessary to avoid pathological worst cases.
812 Almost any choice will do in practice
813
814 - Allthough it seems that a rather large [delta] may perform better
815 than smaller one, measurements have shown that the smallest [delta]
816 of 4 is actually the fastest on a wide range of operations. It
817 especially improves performance on worst-case scenarios like
818 a sequence of ordered insertions.
819
820 Note: in contrast to Adams' paper, we use a ratio of (at least) 2
821 to decide whether a single or double rotation is needed. Allthough
822 he actually proves that this ratio is needed to maintain the
823 invariants, his implementation uses a (invalid) ratio of 1.
824 He is aware of the problem though since he has put a comment in his
825 original source code that he doesn't care about generating a
826 slightly inbalanced tree since it doesn't seem to matter in practice.
827 However (since we use quickcheck :-) we will stick to strictly balanced
828 trees.
829 --------------------------------------------------------------------}
830 delta,ratio :: Int
831 delta = 4
832 ratio = 2
833
834 balance :: a -> Set a -> Set a -> Set a
835 balance x l r
836 | sizeL + sizeR <= 1 = Bin sizeX x l r
837 | sizeR >= delta*sizeL = rotateL x l r
838 | sizeL >= delta*sizeR = rotateR x l r
839 | otherwise = Bin sizeX x l r
840 where
841 sizeL = size l
842 sizeR = size r
843 sizeX = sizeL + sizeR + 1
844
845 -- rotate
846 rotateL :: a -> Set a -> Set a -> Set a
847 rotateL x l r@(Bin _ _ ly ry)
848 | size ly < ratio*size ry = singleL x l r
849 | otherwise = doubleL x l r
850 rotateL _ _ Tip = error "rotateL Tip"
851
852 rotateR :: a -> Set a -> Set a -> Set a
853 rotateR x l@(Bin _ _ ly ry) r
854 | size ry < ratio*size ly = singleR x l r
855 | otherwise = doubleR x l r
856 rotateR _ Tip _ = error "rotateL Tip"
857
858 -- basic rotations
859 singleL, singleR :: a -> Set a -> Set a -> Set a
860 singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
861 singleL _ _ Tip = error "singleL"
862 singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
863 singleR _ Tip _ = error "singleR"
864
865 doubleL, doubleR :: a -> Set a -> Set a -> Set a
866 doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
867 doubleL _ _ _ = error "doubleL"
868 doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
869 doubleR _ _ _ = error "doubleR"
870
871
872 {--------------------------------------------------------------------
873 The bin constructor maintains the size of the tree
874 --------------------------------------------------------------------}
875 bin :: a -> Set a -> Set a -> Set a
876 bin x l r
877 = Bin (size l + size r + 1) x l r
878
879
880 {--------------------------------------------------------------------
881 Utilities
882 --------------------------------------------------------------------}
883 foldlStrict :: (a -> b -> a) -> a -> [b] -> a
884 foldlStrict f z xs
885 = case xs of
886 [] -> z
887 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
888
889
890 {--------------------------------------------------------------------
891 Debugging
892 --------------------------------------------------------------------}
893 -- | /O(n)/. Show the tree that implements the set. The tree is shown
894 -- in a compressed, hanging format.
895 showTree :: Show a => Set a -> String
896 showTree s
897 = showTreeWith True False s
898
899
900 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
901 the tree that implements the set. If @hang@ is
902 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
903 @wide@ is 'True', an extra wide version is shown.
904
905 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
906 > 4
907 > +--2
908 > | +--1
909 > | +--3
910 > +--5
911 >
912 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
913 > 4
914 > |
915 > +--2
916 > | |
917 > | +--1
918 > | |
919 > | +--3
920 > |
921 > +--5
922 >
923 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
924 > +--5
925 > |
926 > 4
927 > |
928 > | +--3
929 > | |
930 > +--2
931 > |
932 > +--1
933
934 -}
935 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
936 showTreeWith hang wide t
937 | hang = (showsTreeHang wide [] t) ""
938 | otherwise = (showsTree wide [] [] t) ""
939
940 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
941 showsTree wide lbars rbars t
942 = case t of
943 Tip -> showsBars lbars . showString "|\n"
944 Bin _ x Tip Tip
945 -> showsBars lbars . shows x . showString "\n"
946 Bin _ x l r
947 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
948 showWide wide rbars .
949 showsBars lbars . shows x . showString "\n" .
950 showWide wide lbars .
951 showsTree wide (withEmpty lbars) (withBar lbars) l
952
953 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
954 showsTreeHang wide bars t
955 = case t of
956 Tip -> showsBars bars . showString "|\n"
957 Bin _ x Tip Tip
958 -> showsBars bars . shows x . showString "\n"
959 Bin _ x l r
960 -> showsBars bars . shows x . showString "\n" .
961 showWide wide bars .
962 showsTreeHang wide (withBar bars) l .
963 showWide wide bars .
964 showsTreeHang wide (withEmpty bars) r
965
966 showWide :: Bool -> [String] -> String -> String
967 showWide wide bars
968 | wide = showString (concat (reverse bars)) . showString "|\n"
969 | otherwise = id
970
971 showsBars :: [String] -> ShowS
972 showsBars bars
973 = case bars of
974 [] -> id
975 _ -> showString (concat (reverse (tail bars))) . showString node
976
977 node :: String
978 node = "+--"
979
980 withBar, withEmpty :: [String] -> [String]
981 withBar bars = "| ":bars
982 withEmpty bars = " ":bars
983
984 {--------------------------------------------------------------------
985 Assertions
986 --------------------------------------------------------------------}
987 -- | /O(n)/. Test if the internal set structure is valid.
988 valid :: Ord a => Set a -> Bool
989 valid t
990 = balanced t && ordered t && validsize t
991
992 ordered :: Ord a => Set a -> Bool
993 ordered t
994 = bounded (const True) (const True) t
995 where
996 bounded lo hi t'
997 = case t' of
998 Tip -> True
999 Bin _ x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
1000
1001 balanced :: Set a -> Bool
1002 balanced t
1003 = case t of
1004 Tip -> True
1005 Bin _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1006 balanced l && balanced r
1007
1008 validsize :: Set a -> Bool
1009 validsize t
1010 = (realsize t == Just (size t))
1011 where
1012 realsize t'
1013 = case t' of
1014 Tip -> Just 0
1015 Bin sz _ l r -> case (realsize l,realsize r) of
1016 (Just n,Just m) | n+m+1 == sz -> Just sz
1017 _ -> Nothing
1018
1019 {-
1020 {--------------------------------------------------------------------
1021 Testing
1022 --------------------------------------------------------------------}
1023 testTree :: [Int] -> Set Int
1024 testTree xs = fromList xs
1025 test1 = testTree [1..20]
1026 test2 = testTree [30,29..10]
1027 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1028
1029 {--------------------------------------------------------------------
1030 QuickCheck
1031 --------------------------------------------------------------------}
1032 qcheck prop
1033 = check config prop
1034 where
1035 config = Config
1036 { configMaxTest = 500
1037 , configMaxFail = 5000
1038 , configSize = \n -> (div n 2 + 3)
1039 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1040 }
1041
1042
1043 {--------------------------------------------------------------------
1044 Arbitrary, reasonably balanced trees
1045 --------------------------------------------------------------------}
1046 instance (Enum a) => Arbitrary (Set a) where
1047 arbitrary = sized (arbtree 0 maxkey)
1048 where maxkey = 10000
1049
1050 arbtree :: (Enum a) => Int -> Int -> Int -> Gen (Set a)
1051 arbtree lo hi n
1052 | n <= 0 = return Tip
1053 | lo >= hi = return Tip
1054 | otherwise = do{ i <- choose (lo,hi)
1055 ; m <- choose (1,30)
1056 ; let (ml,mr) | m==(1::Int)= (1,2)
1057 | m==2 = (2,1)
1058 | m==3 = (1,1)
1059 | otherwise = (2,2)
1060 ; l <- arbtree lo (i-1) (n `div` ml)
1061 ; r <- arbtree (i+1) hi (n `div` mr)
1062 ; return (bin (toEnum i) l r)
1063 }
1064
1065
1066 {--------------------------------------------------------------------
1067 Valid tree's
1068 --------------------------------------------------------------------}
1069 forValid :: (Enum a,Show a,Testable b) => (Set a -> b) -> Property
1070 forValid f
1071 = forAll arbitrary $ \t ->
1072 -- classify (balanced t) "balanced" $
1073 classify (size t == 0) "empty" $
1074 classify (size t > 0 && size t <= 10) "small" $
1075 classify (size t > 10 && size t <= 64) "medium" $
1076 classify (size t > 64) "large" $
1077 balanced t ==> f t
1078
1079 forValidIntTree :: Testable a => (Set Int -> a) -> Property
1080 forValidIntTree f
1081 = forValid f
1082
1083 forValidUnitTree :: Testable a => (Set Int -> a) -> Property
1084 forValidUnitTree f
1085 = forValid f
1086
1087
1088 prop_Valid
1089 = forValidUnitTree $ \t -> valid t
1090
1091 {--------------------------------------------------------------------
1092 Single, Insert, Delete
1093 --------------------------------------------------------------------}
1094 prop_Single :: Int -> Bool
1095 prop_Single x
1096 = (insert x empty == singleton x)
1097
1098 prop_InsertValid :: Int -> Property
1099 prop_InsertValid k
1100 = forValidUnitTree $ \t -> valid (insert k t)
1101
1102 prop_InsertDelete :: Int -> Set Int -> Property
1103 prop_InsertDelete k t
1104 = not (member k t) ==> delete k (insert k t) == t
1105
1106 prop_DeleteValid :: Int -> Property
1107 prop_DeleteValid k
1108 = forValidUnitTree $ \t ->
1109 valid (delete k (insert k t))
1110
1111 {--------------------------------------------------------------------
1112 Balance
1113 --------------------------------------------------------------------}
1114 prop_Join :: Int -> Property
1115 prop_Join x
1116 = forValidUnitTree $ \t ->
1117 let (l,r) = split x t
1118 in valid (join x l r)
1119
1120 prop_Merge :: Int -> Property
1121 prop_Merge x
1122 = forValidUnitTree $ \t ->
1123 let (l,r) = split x t
1124 in valid (merge l r)
1125
1126
1127 {--------------------------------------------------------------------
1128 Union
1129 --------------------------------------------------------------------}
1130 prop_UnionValid :: Property
1131 prop_UnionValid
1132 = forValidUnitTree $ \t1 ->
1133 forValidUnitTree $ \t2 ->
1134 valid (union t1 t2)
1135
1136 prop_UnionInsert :: Int -> Set Int -> Bool
1137 prop_UnionInsert x t
1138 = union t (singleton x) == insert x t
1139
1140 prop_UnionAssoc :: Set Int -> Set Int -> Set Int -> Bool
1141 prop_UnionAssoc t1 t2 t3
1142 = union t1 (union t2 t3) == union (union t1 t2) t3
1143
1144 prop_UnionComm :: Set Int -> Set Int -> Bool
1145 prop_UnionComm t1 t2
1146 = (union t1 t2 == union t2 t1)
1147
1148
1149 prop_DiffValid
1150 = forValidUnitTree $ \t1 ->
1151 forValidUnitTree $ \t2 ->
1152 valid (difference t1 t2)
1153
1154 prop_Diff :: [Int] -> [Int] -> Bool
1155 prop_Diff xs ys
1156 = toAscList (difference (fromList xs) (fromList ys))
1157 == List.sort ((List.\\) (nub xs) (nub ys))
1158
1159 prop_IntValid
1160 = forValidUnitTree $ \t1 ->
1161 forValidUnitTree $ \t2 ->
1162 valid (intersection t1 t2)
1163
1164 prop_Int :: [Int] -> [Int] -> Bool
1165 prop_Int xs ys
1166 = toAscList (intersection (fromList xs) (fromList ys))
1167 == List.sort (nub ((List.intersect) (xs) (ys)))
1168
1169 {--------------------------------------------------------------------
1170 Lists
1171 --------------------------------------------------------------------}
1172 prop_Ordered
1173 = forAll (choose (5,100)) $ \n ->
1174 let xs = [0..n::Int]
1175 in fromAscList xs == fromList xs
1176
1177 prop_List :: [Int] -> Bool
1178 prop_List xs
1179 = (sort (nub xs) == toList (fromList xs))
1180 -}