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