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