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