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