Add Cartesian products and disjoint unions for Set
[packages/containers.git] / Data / Set / Internal.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE BangPatterns #-}
3 {-# LANGUAGE PatternGuards #-}
4 #if __GLASGOW_HASKELL__
5 {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
6 #endif
7 #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
8 {-# LANGUAGE Trustworthy #-}
9 #endif
10 #if __GLASGOW_HASKELL__ >= 708
11 {-# LANGUAGE RoleAnnotations #-}
12 {-# LANGUAGE TypeFamilies #-}
13 #endif
14
15 #include "containers.h"
16
17 -----------------------------------------------------------------------------
18 -- |
19 -- Module : Data.Set.Internal
20 -- Copyright : (c) Daan Leijen 2002
21 -- License : BSD-style
22 -- Maintainer : libraries@haskell.org
23 -- Portability : portable
24 --
25 -- = WARNING
26 --
27 -- This module is considered __internal__.
28 --
29 -- The Package Versioning Policy __does not apply__.
30 --
31 -- This contents of this module may change __in any way whatsoever__
32 -- and __without any warning__ between minor versions of this package.
33 --
34 -- Authors importing this module are expected to track development
35 -- closely.
36 --
37 -- = Description
38 --
39 -- An efficient implementation of sets.
40 --
41 -- These modules are intended to be imported qualified, to avoid name
42 -- clashes with Prelude functions, e.g.
43 --
44 -- > import Data.Set (Set)
45 -- > import qualified Data.Set as Set
46 --
47 -- The implementation of 'Set' is based on /size balanced/ binary trees (or
48 -- trees of /bounded balance/) as described by:
49 --
50 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
51 -- Journal of Functional Programming 3(4):553-562, October 1993,
52 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
53 -- * J. Nievergelt and E.M. Reingold,
54 -- \"/Binary search trees of bounded balance/\",
55 -- SIAM journal of computing 2(1), March 1973.
56 --
57 -- Bounds for 'union', 'intersection', and 'difference' are as given
58 -- by
59 --
60 -- * Guy Blelloch, Daniel Ferizovic, and Yihan Sun,
61 -- \"/Just Join for Parallel Ordered Sets/\",
62 -- <https://arxiv.org/abs/1602.02120v3>.
63 --
64 -- Note that the implementation is /left-biased/ -- the elements of a
65 -- first argument are always preferred to the second, for example in
66 -- 'union' or 'insert'. Of course, left-biasing can only be observed
67 -- when equality is an equivalence relation instead of structural
68 -- equality.
69 --
70 -- /Warning/: The size of the set must not exceed @maxBound::Int@. Violation of
71 -- this condition is not detected and if the size limit is exceeded, the
72 -- behavior of the set is completely undefined.
73 --
74 -- @since 0.5.9
75 -----------------------------------------------------------------------------
76
77 -- [Note: Using INLINABLE]
78 -- ~~~~~~~~~~~~~~~~~~~~~~~
79 -- It is crucial to the performance that the functions specialize on the Ord
80 -- type when possible. GHC 7.0 and higher does this by itself when it sees th
81 -- unfolding of a function -- that is why all public functions are marked
82 -- INLINABLE (that exposes the unfolding).
83
84
85 -- [Note: Using INLINE]
86 -- ~~~~~~~~~~~~~~~~~~~~
87 -- For other compilers and GHC pre 7.0, we mark some of the functions INLINE.
88 -- We mark the functions that just navigate down the tree (lookup, insert,
89 -- delete and similar). That navigation code gets inlined and thus specialized
90 -- when possible. There is a price to pay -- code growth. The code INLINED is
91 -- therefore only the tree navigation, all the real work (rebalancing) is not
92 -- INLINED by using a NOINLINE.
93 --
94 -- All methods marked INLINE have to be nonrecursive -- a 'go' function doing
95 -- the real work is provided.
96
97
98 -- [Note: Type of local 'go' function]
99 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
100 -- If the local 'go' function uses an Ord class, it sometimes heap-allocates
101 -- the Ord dictionary when the 'go' function does not have explicit type.
102 -- In that case we give 'go' explicit type. But this slightly decrease
103 -- performance, as the resulting 'go' function can float out to top level.
104
105
106 -- [Note: Local 'go' functions and capturing]
107 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
108 -- As opposed to IntSet, when 'go' function captures an argument, increased
109 -- heap-allocation can occur: sometimes in a polymorphic function, the 'go'
110 -- floats out of its enclosing function and then it heap-allocates the
111 -- dictionary and the argument. Maybe it floats out too late and strictness
112 -- analyzer cannot see that these could be passed on stack.
113
114 -- [Note: Order of constructors]
115 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
116 -- The order of constructors of Set matters when considering performance.
117 -- Currently in GHC 7.0, when type has 2 constructors, a forward conditional
118 -- jump is made when successfully matching second constructor. Successful match
119 -- of first constructor results in the forward jump not taken.
120 -- On GHC 7.0, reordering constructors from Tip | Bin to Bin | Tip
121 -- improves the benchmark by up to 10% on x86.
122
123 module Data.Set.Internal (
124 -- * Set type
125 Set(..) -- instance Eq,Ord,Show,Read,Data,Typeable
126 , Size
127
128 -- * Operators
129 , (\\)
130
131 -- * Query
132 , null
133 , size
134 , member
135 , notMember
136 , lookupLT
137 , lookupGT
138 , lookupLE
139 , lookupGE
140 , isSubsetOf
141 , isProperSubsetOf
142
143 -- * Construction
144 , empty
145 , singleton
146 , insert
147 , delete
148 , powerSet
149
150 -- * Combine
151 , union
152 , unions
153 , difference
154 , intersection
155 , cartesianProduct
156 , disjointUnion
157
158 -- * Filter
159 , filter
160 , takeWhileAntitone
161 , dropWhileAntitone
162 , spanAntitone
163 , partition
164 , split
165 , splitMember
166 , splitRoot
167
168 -- * Indexed
169 , lookupIndex
170 , findIndex
171 , elemAt
172 , deleteAt
173 , take
174 , drop
175 , splitAt
176
177 -- * Map
178 , map
179 , mapMonotonic
180
181 -- * Folds
182 , foldr
183 , foldl
184 -- ** Strict folds
185 , foldr'
186 , foldl'
187 -- ** Legacy folds
188 , fold
189
190 -- * Min\/Max
191 , lookupMin
192 , lookupMax
193 , findMin
194 , findMax
195 , deleteMin
196 , deleteMax
197 , deleteFindMin
198 , deleteFindMax
199 , maxView
200 , minView
201
202 -- * Conversion
203
204 -- ** List
205 , elems
206 , toList
207 , fromList
208
209 -- ** Ordered list
210 , toAscList
211 , toDescList
212 , fromAscList
213 , fromDistinctAscList
214 , fromDescList
215 , fromDistinctDescList
216
217 -- * Debugging
218 , showTree
219 , showTreeWith
220 , valid
221
222 -- Internals (for testing)
223 , bin
224 , balanced
225 , link
226 , merge
227 ) where
228
229 import Prelude hiding (filter,foldl,foldr,null,map,take,drop,splitAt)
230 import qualified Data.List as List
231 import Data.Bits (shiftL, shiftR)
232 #if !MIN_VERSION_base(4,8,0)
233 import Data.Monoid (Monoid(..))
234 #endif
235 #if MIN_VERSION_base(4,9,0)
236 import Data.Semigroup (Semigroup((<>), stimes), stimesIdempotentMonoid)
237 import Data.Functor.Classes
238 #endif
239 import qualified Data.Foldable as Foldable
240 #if !MIN_VERSION_base(4,8,0)
241 import Data.Foldable (Foldable (foldMap))
242 #endif
243 import Data.Typeable
244 import Control.DeepSeq (NFData(rnf))
245
246 import Utils.Containers.Internal.StrictFold
247 import Utils.Containers.Internal.StrictPair
248 import Utils.Containers.Internal.PtrEquality
249
250 #if __GLASGOW_HASKELL__
251 import GHC.Exts ( build, lazy )
252 #if __GLASGOW_HASKELL__ >= 708
253 import qualified GHC.Exts as GHCExts
254 #endif
255 import Text.Read ( readPrec, Read (..), Lexeme (..), parens, prec
256 , lexP, readListPrecDefault )
257 import Data.Data
258 #endif
259
260
261 {--------------------------------------------------------------------
262 Operators
263 --------------------------------------------------------------------}
264 infixl 9 \\ --
265
266 -- | /O(m*log(n\/m+1)), m <= n/. See 'difference'.
267 (\\) :: Ord a => Set a -> Set a -> Set a
268 m1 \\ m2 = difference m1 m2
269 #if __GLASGOW_HASKELL__
270 {-# INLINABLE (\\) #-}
271 #endif
272
273 {--------------------------------------------------------------------
274 Sets are size balanced trees
275 --------------------------------------------------------------------}
276 -- | A set of values @a@.
277
278 -- See Note: Order of constructors
279 data Set a = Bin {-# UNPACK #-} !Size !a !(Set a) !(Set a)
280 | Tip
281
282 type Size = Int
283
284 #if __GLASGOW_HASKELL__ >= 708
285 type role Set nominal
286 #endif
287
288 instance Ord a => Monoid (Set a) where
289 mempty = empty
290 mconcat = unions
291 #if !(MIN_VERSION_base(4,9,0))
292 mappend = union
293 #else
294 mappend = (<>)
295
296 -- | @since 0.5.7
297 instance Ord a => Semigroup (Set a) where
298 (<>) = union
299 stimes = stimesIdempotentMonoid
300 #endif
301
302
303 instance Foldable.Foldable Set where
304 fold = go
305 where go Tip = mempty
306 go (Bin 1 k _ _) = k
307 go (Bin _ k l r) = go l `mappend` (k `mappend` go r)
308 {-# INLINABLE fold #-}
309 foldr = foldr
310 {-# INLINE foldr #-}
311 foldl = foldl
312 {-# INLINE foldl #-}
313 foldMap f t = go t
314 where go Tip = mempty
315 go (Bin 1 k _ _) = f k
316 go (Bin _ k l r) = go l `mappend` (f k `mappend` go r)
317 {-# INLINE foldMap #-}
318
319 #if MIN_VERSION_base(4,6,0)
320 foldl' = foldl'
321 {-# INLINE foldl' #-}
322 foldr' = foldr'
323 {-# INLINE foldr' #-}
324 #endif
325 #if MIN_VERSION_base(4,8,0)
326 length = size
327 {-# INLINE length #-}
328 null = null
329 {-# INLINE null #-}
330 toList = toList
331 {-# INLINE toList #-}
332 elem = go
333 where go !_ Tip = False
334 go x (Bin _ y l r) = x == y || go x l || go x r
335 {-# INLINABLE elem #-}
336 minimum = findMin
337 {-# INLINE minimum #-}
338 maximum = findMax
339 {-# INLINE maximum #-}
340 sum = foldl' (+) 0
341 {-# INLINABLE sum #-}
342 product = foldl' (*) 1
343 {-# INLINABLE product #-}
344 #endif
345
346
347 #if __GLASGOW_HASKELL__
348
349 {--------------------------------------------------------------------
350 A Data instance
351 --------------------------------------------------------------------}
352
353 -- This instance preserves data abstraction at the cost of inefficiency.
354 -- We provide limited reflection services for the sake of data abstraction.
355
356 instance (Data a, Ord a) => Data (Set a) where
357 gfoldl f z set = z fromList `f` (toList set)
358 toConstr _ = fromListConstr
359 gunfold k z c = case constrIndex c of
360 1 -> k (z fromList)
361 _ -> error "gunfold"
362 dataTypeOf _ = setDataType
363 dataCast1 f = gcast1 f
364
365 fromListConstr :: Constr
366 fromListConstr = mkConstr setDataType "fromList" [] Prefix
367
368 setDataType :: DataType
369 setDataType = mkDataType "Data.Set.Internal.Set" [fromListConstr]
370
371 #endif
372
373 {--------------------------------------------------------------------
374 Query
375 --------------------------------------------------------------------}
376 -- | /O(1)/. Is this the empty set?
377 null :: Set a -> Bool
378 null Tip = True
379 null (Bin {}) = False
380 {-# INLINE null #-}
381
382 -- | /O(1)/. The number of elements in the set.
383 size :: Set a -> Int
384 size Tip = 0
385 size (Bin sz _ _ _) = sz
386 {-# INLINE size #-}
387
388 -- | /O(log n)/. Is the element in the set?
389 member :: Ord a => a -> Set a -> Bool
390 member = go
391 where
392 go !_ Tip = False
393 go x (Bin _ y l r) = case compare x y of
394 LT -> go x l
395 GT -> go x r
396 EQ -> True
397 #if __GLASGOW_HASKELL__
398 {-# INLINABLE member #-}
399 #else
400 {-# INLINE member #-}
401 #endif
402
403 -- | /O(log n)/. Is the element not in the set?
404 notMember :: Ord a => a -> Set a -> Bool
405 notMember a t = not $ member a t
406 #if __GLASGOW_HASKELL__
407 {-# INLINABLE notMember #-}
408 #else
409 {-# INLINE notMember #-}
410 #endif
411
412 -- | /O(log n)/. Find largest element smaller than the given one.
413 --
414 -- > lookupLT 3 (fromList [3, 5]) == Nothing
415 -- > lookupLT 5 (fromList [3, 5]) == Just 3
416 lookupLT :: Ord a => a -> Set a -> Maybe a
417 lookupLT = goNothing
418 where
419 goNothing !_ Tip = Nothing
420 goNothing x (Bin _ y l r) | x <= y = goNothing x l
421 | otherwise = goJust x y r
422
423 goJust !_ best Tip = Just best
424 goJust x best (Bin _ y l r) | x <= y = goJust x best l
425 | otherwise = goJust x y r
426 #if __GLASGOW_HASKELL__
427 {-# INLINABLE lookupLT #-}
428 #else
429 {-# INLINE lookupLT #-}
430 #endif
431
432 -- | /O(log n)/. Find smallest element greater than the given one.
433 --
434 -- > lookupGT 4 (fromList [3, 5]) == Just 5
435 -- > lookupGT 5 (fromList [3, 5]) == Nothing
436 lookupGT :: Ord a => a -> Set a -> Maybe a
437 lookupGT = goNothing
438 where
439 goNothing !_ Tip = Nothing
440 goNothing x (Bin _ y l r) | x < y = goJust x y l
441 | otherwise = goNothing x r
442
443 goJust !_ best Tip = Just best
444 goJust x best (Bin _ y l r) | x < y = goJust x y l
445 | otherwise = goJust x best r
446 #if __GLASGOW_HASKELL__
447 {-# INLINABLE lookupGT #-}
448 #else
449 {-# INLINE lookupGT #-}
450 #endif
451
452 -- | /O(log n)/. Find largest element smaller or equal to the given one.
453 --
454 -- > lookupLE 2 (fromList [3, 5]) == Nothing
455 -- > lookupLE 4 (fromList [3, 5]) == Just 3
456 -- > lookupLE 5 (fromList [3, 5]) == Just 5
457 lookupLE :: Ord a => a -> Set a -> Maybe a
458 lookupLE = goNothing
459 where
460 goNothing !_ Tip = Nothing
461 goNothing x (Bin _ y l r) = case compare x y of LT -> goNothing x l
462 EQ -> Just y
463 GT -> goJust x y r
464
465 goJust !_ best Tip = Just best
466 goJust x best (Bin _ y l r) = case compare x y of LT -> goJust x best l
467 EQ -> Just y
468 GT -> goJust x y r
469 #if __GLASGOW_HASKELL__
470 {-# INLINABLE lookupLE #-}
471 #else
472 {-# INLINE lookupLE #-}
473 #endif
474
475 -- | /O(log n)/. Find smallest element greater or equal to the given one.
476 --
477 -- > lookupGE 3 (fromList [3, 5]) == Just 3
478 -- > lookupGE 4 (fromList [3, 5]) == Just 5
479 -- > lookupGE 6 (fromList [3, 5]) == Nothing
480 lookupGE :: Ord a => a -> Set a -> Maybe a
481 lookupGE = goNothing
482 where
483 goNothing !_ Tip = Nothing
484 goNothing x (Bin _ y l r) = case compare x y of LT -> goJust x y l
485 EQ -> Just y
486 GT -> goNothing x r
487
488 goJust !_ best Tip = Just best
489 goJust x best (Bin _ y l r) = case compare x y of LT -> goJust x y l
490 EQ -> Just y
491 GT -> goJust x best r
492 #if __GLASGOW_HASKELL__
493 {-# INLINABLE lookupGE #-}
494 #else
495 {-# INLINE lookupGE #-}
496 #endif
497
498 {--------------------------------------------------------------------
499 Construction
500 --------------------------------------------------------------------}
501 -- | /O(1)/. The empty set.
502 empty :: Set a
503 empty = Tip
504 {-# INLINE empty #-}
505
506 -- | /O(1)/. Create a singleton set.
507 singleton :: a -> Set a
508 singleton x = Bin 1 x Tip Tip
509 {-# INLINE singleton #-}
510
511 {--------------------------------------------------------------------
512 Insertion, Deletion
513 --------------------------------------------------------------------}
514 -- | /O(log n)/. Insert an element in a set.
515 -- If the set already contains an element equal to the given value,
516 -- it is replaced with the new value.
517
518 -- See Note: Type of local 'go' function
519 -- See Note: Avoiding worker/wrapper (in Data.Map.Internal)
520 insert :: Ord a => a -> Set a -> Set a
521 insert x0 = go x0 x0
522 where
523 go :: Ord a => a -> a -> Set a -> Set a
524 go orig !_ Tip = singleton (lazy orig)
525 go orig !x t@(Bin sz y l r) = case compare x y of
526 LT | l' `ptrEq` l -> t
527 | otherwise -> balanceL y l' r
528 where !l' = go orig x l
529 GT | r' `ptrEq` r -> t
530 | otherwise -> balanceR y l r'
531 where !r' = go orig x r
532 EQ | lazy orig `seq` (orig `ptrEq` y) -> t
533 | otherwise -> Bin sz (lazy orig) l r
534 #if __GLASGOW_HASKELL__
535 {-# INLINABLE insert #-}
536 #else
537 {-# INLINE insert #-}
538 #endif
539
540 #ifndef __GLASGOW_HASKELL__
541 lazy :: a -> a
542 lazy a = a
543 #endif
544
545 -- Insert an element to the set only if it is not in the set.
546 -- Used by `union`.
547
548 -- See Note: Type of local 'go' function
549 -- See Note: Avoiding worker/wrapper (in Data.Map.Internal)
550 insertR :: Ord a => a -> Set a -> Set a
551 insertR x0 = go x0 x0
552 where
553 go :: Ord a => a -> a -> Set a -> Set a
554 go orig !_ Tip = singleton (lazy orig)
555 go orig !x t@(Bin _ y l r) = case compare x y of
556 LT | l' `ptrEq` l -> t
557 | otherwise -> balanceL y l' r
558 where !l' = go orig x l
559 GT | r' `ptrEq` r -> t
560 | otherwise -> balanceR y l r'
561 where !r' = go orig x r
562 EQ -> t
563 #if __GLASGOW_HASKELL__
564 {-# INLINABLE insertR #-}
565 #else
566 {-# INLINE insertR #-}
567 #endif
568
569 -- | /O(log n)/. Delete an element from a set.
570
571 -- See Note: Type of local 'go' function
572 delete :: Ord a => a -> Set a -> Set a
573 delete = go
574 where
575 go :: Ord a => a -> Set a -> Set a
576 go !_ Tip = Tip
577 go x t@(Bin _ y l r) = case compare x y of
578 LT | l' `ptrEq` l -> t
579 | otherwise -> balanceR y l' r
580 where !l' = go x l
581 GT | r' `ptrEq` r -> t
582 | otherwise -> balanceL y l r'
583 where !r' = go x r
584 EQ -> glue l r
585 #if __GLASGOW_HASKELL__
586 {-# INLINABLE delete #-}
587 #else
588 {-# INLINE delete #-}
589 #endif
590
591 {--------------------------------------------------------------------
592 Subset
593 --------------------------------------------------------------------}
594 -- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
595 isProperSubsetOf :: Ord a => Set a -> Set a -> Bool
596 isProperSubsetOf s1 s2
597 = (size s1 < size s2) && (isSubsetOf s1 s2)
598 #if __GLASGOW_HASKELL__
599 {-# INLINABLE isProperSubsetOf #-}
600 #endif
601
602
603 -- | /O(n+m)/. Is this a subset?
604 -- @(s1 `isSubsetOf` s2)@ tells whether @s1@ is a subset of @s2@.
605 isSubsetOf :: Ord a => Set a -> Set a -> Bool
606 isSubsetOf t1 t2
607 = (size t1 <= size t2) && (isSubsetOfX t1 t2)
608 #if __GLASGOW_HASKELL__
609 {-# INLINABLE isSubsetOf #-}
610 #endif
611
612 isSubsetOfX :: Ord a => Set a -> Set a -> Bool
613 isSubsetOfX Tip _ = True
614 isSubsetOfX _ Tip = False
615 isSubsetOfX (Bin _ x l r) t
616 = found && isSubsetOfX l lt && isSubsetOfX r gt
617 where
618 (lt,found,gt) = splitMember x t
619 #if __GLASGOW_HASKELL__
620 {-# INLINABLE isSubsetOfX #-}
621 #endif
622
623
624 {--------------------------------------------------------------------
625 Minimal, Maximal
626 --------------------------------------------------------------------}
627
628 -- We perform call-pattern specialization manually on lookupMin
629 -- and lookupMax. Otherwise, GHC doesn't seem to do it, which is
630 -- unfortunate if, for example, someone uses findMin or findMax.
631
632 lookupMinSure :: a -> Set a -> a
633 lookupMinSure x Tip = x
634 lookupMinSure _ (Bin _ x l _) = lookupMinSure x l
635
636 -- | /O(log n)/. The minimal element of a set.
637 --
638 -- @since 0.5.9
639
640 lookupMin :: Set a -> Maybe a
641 lookupMin Tip = Nothing
642 lookupMin (Bin _ x l _) = Just $! lookupMinSure x l
643
644 -- | /O(log n)/. The minimal element of a set.
645 findMin :: Set a -> a
646 findMin t
647 | Just r <- lookupMin t = r
648 | otherwise = error "Set.findMin: empty set has no minimal element"
649
650 lookupMaxSure :: a -> Set a -> a
651 lookupMaxSure x Tip = x
652 lookupMaxSure _ (Bin _ x _ r) = lookupMaxSure x r
653
654 -- | /O(log n)/. The maximal element of a set.
655 --
656 -- @since 0.5.9
657
658 lookupMax :: Set a -> Maybe a
659 lookupMax Tip = Nothing
660 lookupMax (Bin _ x _ r) = Just $! lookupMaxSure x r
661
662 -- | /O(log n)/. The maximal element of a set.
663 findMax :: Set a -> a
664 findMax t
665 | Just r <- lookupMax t = r
666 | otherwise = error "Set.findMax: empty set has no maximal element"
667
668 -- | /O(log n)/. Delete the minimal element. Returns an empty set if the set is empty.
669 deleteMin :: Set a -> Set a
670 deleteMin (Bin _ _ Tip r) = r
671 deleteMin (Bin _ x l r) = balanceR x (deleteMin l) r
672 deleteMin Tip = Tip
673
674 -- | /O(log n)/. Delete the maximal element. Returns an empty set if the set is empty.
675 deleteMax :: Set a -> Set a
676 deleteMax (Bin _ _ l Tip) = l
677 deleteMax (Bin _ x l r) = balanceL x l (deleteMax r)
678 deleteMax Tip = Tip
679
680 {--------------------------------------------------------------------
681 Union.
682 --------------------------------------------------------------------}
683 -- | The union of a list of sets: (@'unions' == 'foldl' 'union' 'empty'@).
684 unions :: Ord a => [Set a] -> Set a
685 unions = foldlStrict union empty
686 #if __GLASGOW_HASKELL__
687 {-# INLINABLE unions #-}
688 #endif
689
690 -- | /O(m*log(n\/m + 1)), m <= n/. The union of two sets, preferring the first set when
691 -- equal elements are encountered.
692 union :: Ord a => Set a -> Set a -> Set a
693 union t1 Tip = t1
694 union t1 (Bin _ x Tip Tip) = insertR x t1
695 union (Bin _ x Tip Tip) t2 = insert x t2
696 union Tip t2 = t2
697 union t1@(Bin _ x l1 r1) t2 = case splitS x t2 of
698 (l2 :*: r2)
699 | l1l2 `ptrEq` l1 && r1r2 `ptrEq` r1 -> t1
700 | otherwise -> link x l1l2 r1r2
701 where !l1l2 = union l1 l2
702 !r1r2 = union r1 r2
703 #if __GLASGOW_HASKELL__
704 {-# INLINABLE union #-}
705 #endif
706
707 {--------------------------------------------------------------------
708 Difference
709 --------------------------------------------------------------------}
710 -- | /O(m*log(n\/m + 1)), m <= n/. Difference of two sets.
711 difference :: Ord a => Set a -> Set a -> Set a
712 difference Tip _ = Tip
713 difference t1 Tip = t1
714 difference t1 (Bin _ x l2 r2) = case split x t1 of
715 (l1, r1)
716 | size l1l2 + size r1r2 == size t1 -> t1
717 | otherwise -> merge l1l2 r1r2
718 where !l1l2 = difference l1 l2
719 !r1r2 = difference r1 r2
720 #if __GLASGOW_HASKELL__
721 {-# INLINABLE difference #-}
722 #endif
723
724 {--------------------------------------------------------------------
725 Intersection
726 --------------------------------------------------------------------}
727 -- | /O(m*log(n\/m + 1)), m <= n/. The intersection of two sets.
728 -- Elements of the result come from the first set, so for example
729 --
730 -- > import qualified Data.Set as S
731 -- > data AB = A | B deriving Show
732 -- > instance Ord AB where compare _ _ = EQ
733 -- > instance Eq AB where _ == _ = True
734 -- > main = print (S.singleton A `S.intersection` S.singleton B,
735 -- > S.singleton B `S.intersection` S.singleton A)
736 --
737 -- prints @(fromList [A],fromList [B])@.
738 intersection :: Ord a => Set a -> Set a -> Set a
739 intersection Tip _ = Tip
740 intersection _ Tip = Tip
741 intersection t1@(Bin _ x l1 r1) t2
742 | b = if l1l2 `ptrEq` l1 && r1r2 `ptrEq` r1
743 then t1
744 else link x l1l2 r1r2
745 | otherwise = merge l1l2 r1r2
746 where
747 !(l2, b, r2) = splitMember x t2
748 !l1l2 = intersection l1 l2
749 !r1r2 = intersection r1 r2
750 #if __GLASGOW_HASKELL__
751 {-# INLINABLE intersection #-}
752 #endif
753
754 {--------------------------------------------------------------------
755 Filter and partition
756 --------------------------------------------------------------------}
757 -- | /O(n)/. Filter all elements that satisfy the predicate.
758 filter :: (a -> Bool) -> Set a -> Set a
759 filter _ Tip = Tip
760 filter p t@(Bin _ x l r)
761 | p x = if l `ptrEq` l' && r `ptrEq` r'
762 then t
763 else link x l' r'
764 | otherwise = merge l' r'
765 where
766 !l' = filter p l
767 !r' = filter p r
768
769 -- | /O(n)/. Partition the set into two sets, one with all elements that satisfy
770 -- the predicate and one with all elements that don't satisfy the predicate.
771 -- See also 'split'.
772 partition :: (a -> Bool) -> Set a -> (Set a,Set a)
773 partition p0 t0 = toPair $ go p0 t0
774 where
775 go _ Tip = (Tip :*: Tip)
776 go p t@(Bin _ x l r) = case (go p l, go p r) of
777 ((l1 :*: l2), (r1 :*: r2))
778 | p x -> (if l1 `ptrEq` l && r1 `ptrEq` r
779 then t
780 else link x l1 r1) :*: merge l2 r2
781 | otherwise -> merge l1 r1 :*:
782 (if l2 `ptrEq` l && r2 `ptrEq` r
783 then t
784 else link x l2 r2)
785
786 {----------------------------------------------------------------------
787 Map
788 ----------------------------------------------------------------------}
789
790 -- | /O(n*log n)/.
791 -- @'map' f s@ is the set obtained by applying @f@ to each element of @s@.
792 --
793 -- It's worth noting that the size of the result may be smaller if,
794 -- for some @(x,y)@, @x \/= y && f x == f y@
795
796 map :: Ord b => (a->b) -> Set a -> Set b
797 map f = fromList . List.map f . toList
798 #if __GLASGOW_HASKELL__
799 {-# INLINABLE map #-}
800 #endif
801
802 -- | /O(n)/. The
803 --
804 -- @'mapMonotonic' f s == 'map' f s@, but works only when @f@ is strictly increasing.
805 -- /The precondition is not checked./
806 -- Semi-formally, we have:
807 --
808 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
809 -- > ==> mapMonotonic f s == map f s
810 -- > where ls = toList s
811
812 mapMonotonic :: (a->b) -> Set a -> Set b
813 mapMonotonic _ Tip = Tip
814 mapMonotonic f (Bin sz x l r) = Bin sz (f x) (mapMonotonic f l) (mapMonotonic f r)
815
816 {--------------------------------------------------------------------
817 Fold
818 --------------------------------------------------------------------}
819 -- | /O(n)/. Fold the elements in the set using the given right-associative
820 -- binary operator. This function is an equivalent of 'foldr' and is present
821 -- for compatibility only.
822 --
823 -- /Please note that fold will be deprecated in the future and removed./
824 fold :: (a -> b -> b) -> b -> Set a -> b
825 fold = foldr
826 {-# INLINE fold #-}
827
828 -- | /O(n)/. Fold the elements in the set using the given right-associative
829 -- binary operator, such that @'foldr' f z == 'Prelude.foldr' f z . 'toAscList'@.
830 --
831 -- For example,
832 --
833 -- > toAscList set = foldr (:) [] set
834 foldr :: (a -> b -> b) -> b -> Set a -> b
835 foldr f z = go z
836 where
837 go z' Tip = z'
838 go z' (Bin _ x l r) = go (f x (go z' r)) l
839 {-# INLINE foldr #-}
840
841 -- | /O(n)/. A strict version of 'foldr'. Each application of the operator is
842 -- evaluated before using the result in the next application. This
843 -- function is strict in the starting value.
844 foldr' :: (a -> b -> b) -> b -> Set a -> b
845 foldr' f z = go z
846 where
847 go !z' Tip = z'
848 go z' (Bin _ x l r) = go (f x (go z' r)) l
849 {-# INLINE foldr' #-}
850
851 -- | /O(n)/. Fold the elements in the set using the given left-associative
852 -- binary operator, such that @'foldl' f z == 'Prelude.foldl' f z . 'toAscList'@.
853 --
854 -- For example,
855 --
856 -- > toDescList set = foldl (flip (:)) [] set
857 foldl :: (a -> b -> a) -> a -> Set b -> a
858 foldl f z = go z
859 where
860 go z' Tip = z'
861 go z' (Bin _ x l r) = go (f (go z' l) x) r
862 {-# INLINE foldl #-}
863
864 -- | /O(n)/. A strict version of 'foldl'. Each application of the operator is
865 -- evaluated before using the result in the next application. This
866 -- function is strict in the starting value.
867 foldl' :: (a -> b -> a) -> a -> Set b -> a
868 foldl' f z = go z
869 where
870 go !z' Tip = z'
871 go z' (Bin _ x l r) = go (f (go z' l) x) r
872 {-# INLINE foldl' #-}
873
874 {--------------------------------------------------------------------
875 List variations
876 --------------------------------------------------------------------}
877 -- | /O(n)/. An alias of 'toAscList'. The elements of a set in ascending order.
878 -- Subject to list fusion.
879 elems :: Set a -> [a]
880 elems = toAscList
881
882 {--------------------------------------------------------------------
883 Lists
884 --------------------------------------------------------------------}
885 #if __GLASGOW_HASKELL__ >= 708
886 -- | @since 0.5.6.2
887 instance (Ord a) => GHCExts.IsList (Set a) where
888 type Item (Set a) = a
889 fromList = fromList
890 toList = toList
891 #endif
892
893 -- | /O(n)/. Convert the set to a list of elements. Subject to list fusion.
894 toList :: Set a -> [a]
895 toList = toAscList
896
897 -- | /O(n)/. Convert the set to an ascending list of elements. Subject to list fusion.
898 toAscList :: Set a -> [a]
899 toAscList = foldr (:) []
900
901 -- | /O(n)/. Convert the set to a descending list of elements. Subject to list
902 -- fusion.
903 toDescList :: Set a -> [a]
904 toDescList = foldl (flip (:)) []
905
906 -- List fusion for the list generating functions.
907 #if __GLASGOW_HASKELL__
908 -- The foldrFB and foldlFB are foldr and foldl equivalents, used for list fusion.
909 -- They are important to convert unfused to{Asc,Desc}List back, see mapFB in prelude.
910 foldrFB :: (a -> b -> b) -> b -> Set a -> b
911 foldrFB = foldr
912 {-# INLINE[0] foldrFB #-}
913 foldlFB :: (a -> b -> a) -> a -> Set b -> a
914 foldlFB = foldl
915 {-# INLINE[0] foldlFB #-}
916
917 -- Inline elems and toList, so that we need to fuse only toAscList.
918 {-# INLINE elems #-}
919 {-# INLINE toList #-}
920
921 -- The fusion is enabled up to phase 2 included. If it does not succeed,
922 -- convert in phase 1 the expanded to{Asc,Desc}List calls back to
923 -- to{Asc,Desc}List. In phase 0, we inline fold{lr}FB (which were used in
924 -- a list fusion, otherwise it would go away in phase 1), and let compiler do
925 -- whatever it wants with to{Asc,Desc}List -- it was forbidden to inline it
926 -- before phase 0, otherwise the fusion rules would not fire at all.
927 {-# NOINLINE[0] toAscList #-}
928 {-# NOINLINE[0] toDescList #-}
929 {-# RULES "Set.toAscList" [~1] forall s . toAscList s = build (\c n -> foldrFB c n s) #-}
930 {-# RULES "Set.toAscListBack" [1] foldrFB (:) [] = toAscList #-}
931 {-# RULES "Set.toDescList" [~1] forall s . toDescList s = build (\c n -> foldlFB (\xs x -> c x xs) n s) #-}
932 {-# RULES "Set.toDescListBack" [1] foldlFB (\xs x -> x : xs) [] = toDescList #-}
933 #endif
934
935 -- | /O(n*log n)/. Create a set from a list of elements.
936 --
937 -- If the elements are ordered, a linear-time implementation is used,
938 -- with the performance equal to 'fromDistinctAscList'.
939
940 -- For some reason, when 'singleton' is used in fromList or in
941 -- create, it is not inlined, so we inline it manually.
942 fromList :: Ord a => [a] -> Set a
943 fromList [] = Tip
944 fromList [x] = Bin 1 x Tip Tip
945 fromList (x0 : xs0) | not_ordered x0 xs0 = fromList' (Bin 1 x0 Tip Tip) xs0
946 | otherwise = go (1::Int) (Bin 1 x0 Tip Tip) xs0
947 where
948 not_ordered _ [] = False
949 not_ordered x (y : _) = x >= y
950 {-# INLINE not_ordered #-}
951
952 fromList' t0 xs = foldlStrict ins t0 xs
953 where ins t x = insert x t
954
955 go !_ t [] = t
956 go _ t [x] = insertMax x t
957 go s l xs@(x : xss) | not_ordered x xss = fromList' l xs
958 | otherwise = case create s xss of
959 (r, ys, []) -> go (s `shiftL` 1) (link x l r) ys
960 (r, _, ys) -> fromList' (link x l r) ys
961
962 -- The create is returning a triple (tree, xs, ys). Both xs and ys
963 -- represent not yet processed elements and only one of them can be nonempty.
964 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
965 -- and must be inserted using fromList'. Otherwise the keys have been
966 -- ordered so far.
967 create !_ [] = (Tip, [], [])
968 create s xs@(x : xss)
969 | s == 1 = if not_ordered x xss then (Bin 1 x Tip Tip, [], xss)
970 else (Bin 1 x Tip Tip, xss, [])
971 | otherwise = case create (s `shiftR` 1) xs of
972 res@(_, [], _) -> res
973 (l, [y], zs) -> (insertMax y l, [], zs)
974 (l, ys@(y:yss), _) | not_ordered y yss -> (l, [], ys)
975 | otherwise -> case create (s `shiftR` 1) yss of
976 (r, zs, ws) -> (link y l r, zs, ws)
977 #if __GLASGOW_HASKELL__
978 {-# INLINABLE fromList #-}
979 #endif
980
981 {--------------------------------------------------------------------
982 Building trees from ascending/descending lists can be done in linear time.
983
984 Note that if [xs] is ascending that:
985 fromAscList xs == fromList xs
986 --------------------------------------------------------------------}
987 -- | /O(n)/. Build a set from an ascending list in linear time.
988 -- /The precondition (input list is ascending) is not checked./
989 fromAscList :: Eq a => [a] -> Set a
990 fromAscList xs = fromDistinctAscList (combineEq xs)
991 #if __GLASGOW_HASKELL__
992 {-# INLINABLE fromAscList #-}
993 #endif
994
995 -- | /O(n)/. Build a set from a descending list in linear time.
996 -- /The precondition (input list is descending) is not checked./
997 --
998 -- @since 0.5.8
999 fromDescList :: Eq a => [a] -> Set a
1000 fromDescList xs = fromDistinctDescList (combineEq xs)
1001 #if __GLASGOW_HASKELL__
1002 {-# INLINABLE fromDescList #-}
1003 #endif
1004
1005 -- [combineEq xs] combines equal elements with [const] in an ordered list [xs]
1006 --
1007 -- TODO: combineEq allocates an intermediate list. It *should* be better to
1008 -- make fromAscListBy and fromDescListBy the fundamental operations, and to
1009 -- implement the rest using those.
1010 combineEq :: Eq a => [a] -> [a]
1011 combineEq [] = []
1012 combineEq (x : xs) = combineEq' x xs
1013 where
1014 combineEq' z [] = [z]
1015 combineEq' z (y:ys)
1016 | z == y = combineEq' z ys
1017 | otherwise = z : combineEq' y ys
1018
1019 -- | /O(n)/. Build a set from an ascending list of distinct elements in linear time.
1020 -- /The precondition (input list is strictly ascending) is not checked./
1021
1022 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1023 -- create, it is not inlined, so we inline it manually.
1024 fromDistinctAscList :: [a] -> Set a
1025 fromDistinctAscList [] = Tip
1026 fromDistinctAscList (x0 : xs0) = go (1::Int) (Bin 1 x0 Tip Tip) xs0
1027 where
1028 go !_ t [] = t
1029 go s l (x : xs) = case create s xs of
1030 (r :*: ys) -> let !t' = link x l r
1031 in go (s `shiftL` 1) t' ys
1032
1033 create !_ [] = (Tip :*: [])
1034 create s xs@(x : xs')
1035 | s == 1 = (Bin 1 x Tip Tip :*: xs')
1036 | otherwise = case create (s `shiftR` 1) xs of
1037 res@(_ :*: []) -> res
1038 (l :*: (y:ys)) -> case create (s `shiftR` 1) ys of
1039 (r :*: zs) -> (link y l r :*: zs)
1040
1041 -- | /O(n)/. Build a set from a descending list of distinct elements in linear time.
1042 -- /The precondition (input list is strictly descending) is not checked./
1043
1044 -- For some reason, when 'singleton' is used in fromDistinctDescList or in
1045 -- create, it is not inlined, so we inline it manually.
1046 --
1047 -- @since 0.5.8
1048 fromDistinctDescList :: [a] -> Set a
1049 fromDistinctDescList [] = Tip
1050 fromDistinctDescList (x0 : xs0) = go (1::Int) (Bin 1 x0 Tip Tip) xs0
1051 where
1052 go !_ t [] = t
1053 go s r (x : xs) = case create s xs of
1054 (l :*: ys) -> let !t' = link x l r
1055 in go (s `shiftL` 1) t' ys
1056
1057 create !_ [] = (Tip :*: [])
1058 create s xs@(x : xs')
1059 | s == 1 = (Bin 1 x Tip Tip :*: xs')
1060 | otherwise = case create (s `shiftR` 1) xs of
1061 res@(_ :*: []) -> res
1062 (r :*: (y:ys)) -> case create (s `shiftR` 1) ys of
1063 (l :*: zs) -> (link y l r :*: zs)
1064
1065 {--------------------------------------------------------------------
1066 Eq converts the set to a list. In a lazy setting, this
1067 actually seems one of the faster methods to compare two trees
1068 and it is certainly the simplest :-)
1069 --------------------------------------------------------------------}
1070 instance Eq a => Eq (Set a) where
1071 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
1072
1073 {--------------------------------------------------------------------
1074 Ord
1075 --------------------------------------------------------------------}
1076
1077 instance Ord a => Ord (Set a) where
1078 compare s1 s2 = compare (toAscList s1) (toAscList s2)
1079
1080 {--------------------------------------------------------------------
1081 Show
1082 --------------------------------------------------------------------}
1083 instance Show a => Show (Set a) where
1084 showsPrec p xs = showParen (p > 10) $
1085 showString "fromList " . shows (toList xs)
1086
1087 #if MIN_VERSION_base(4,9,0)
1088 -- | @since 0.5.9
1089 instance Eq1 Set where
1090 liftEq eq m n =
1091 size m == size n && liftEq eq (toList m) (toList n)
1092
1093 -- | @since 0.5.9
1094 instance Ord1 Set where
1095 liftCompare cmp m n =
1096 liftCompare cmp (toList m) (toList n)
1097
1098 -- | @since 0.5.9
1099 instance Show1 Set where
1100 liftShowsPrec sp sl d m =
1101 showsUnaryWith (liftShowsPrec sp sl) "fromList" d (toList m)
1102 #endif
1103
1104 {--------------------------------------------------------------------
1105 Read
1106 --------------------------------------------------------------------}
1107 instance (Read a, Ord a) => Read (Set a) where
1108 #ifdef __GLASGOW_HASKELL__
1109 readPrec = parens $ prec 10 $ do
1110 Ident "fromList" <- lexP
1111 xs <- readPrec
1112 return (fromList xs)
1113
1114 readListPrec = readListPrecDefault
1115 #else
1116 readsPrec p = readParen (p > 10) $ \ r -> do
1117 ("fromList",s) <- lex r
1118 (xs,t) <- reads s
1119 return (fromList xs,t)
1120 #endif
1121
1122 {--------------------------------------------------------------------
1123 Typeable/Data
1124 --------------------------------------------------------------------}
1125
1126 INSTANCE_TYPEABLE1(Set)
1127
1128 {--------------------------------------------------------------------
1129 NFData
1130 --------------------------------------------------------------------}
1131
1132 instance NFData a => NFData (Set a) where
1133 rnf Tip = ()
1134 rnf (Bin _ y l r) = rnf y `seq` rnf l `seq` rnf r
1135
1136 {--------------------------------------------------------------------
1137 Split
1138 --------------------------------------------------------------------}
1139 -- | /O(log n)/. The expression (@'split' x set@) is a pair @(set1,set2)@
1140 -- where @set1@ comprises the elements of @set@ less than @x@ and @set2@
1141 -- comprises the elements of @set@ greater than @x@.
1142 split :: Ord a => a -> Set a -> (Set a,Set a)
1143 split x t = toPair $ splitS x t
1144 {-# INLINABLE split #-}
1145
1146 splitS :: Ord a => a -> Set a -> StrictPair (Set a) (Set a)
1147 splitS _ Tip = (Tip :*: Tip)
1148 splitS x (Bin _ y l r)
1149 = case compare x y of
1150 LT -> let (lt :*: gt) = splitS x l in (lt :*: link y gt r)
1151 GT -> let (lt :*: gt) = splitS x r in (link y l lt :*: gt)
1152 EQ -> (l :*: r)
1153 {-# INLINABLE splitS #-}
1154
1155 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
1156 -- element was found in the original set.
1157 splitMember :: Ord a => a -> Set a -> (Set a,Bool,Set a)
1158 splitMember _ Tip = (Tip, False, Tip)
1159 splitMember x (Bin _ y l r)
1160 = case compare x y of
1161 LT -> let (lt, found, gt) = splitMember x l
1162 !gt' = link y gt r
1163 in (lt, found, gt')
1164 GT -> let (lt, found, gt) = splitMember x r
1165 !lt' = link y l lt
1166 in (lt', found, gt)
1167 EQ -> (l, True, r)
1168 #if __GLASGOW_HASKELL__
1169 {-# INLINABLE splitMember #-}
1170 #endif
1171
1172 {--------------------------------------------------------------------
1173 Indexing
1174 --------------------------------------------------------------------}
1175
1176 -- | /O(log n)/. Return the /index/ of an element, which is its zero-based
1177 -- index in the sorted sequence of elements. The index is a number from /0/ up
1178 -- to, but not including, the 'size' of the set. Calls 'error' when the element
1179 -- is not a 'member' of the set.
1180 --
1181 -- > findIndex 2 (fromList [5,3]) Error: element is not in the set
1182 -- > findIndex 3 (fromList [5,3]) == 0
1183 -- > findIndex 5 (fromList [5,3]) == 1
1184 -- > findIndex 6 (fromList [5,3]) Error: element is not in the set
1185 --
1186 -- @since 0.5.4
1187
1188 -- See Note: Type of local 'go' function
1189 findIndex :: Ord a => a -> Set a -> Int
1190 findIndex = go 0
1191 where
1192 go :: Ord a => Int -> a -> Set a -> Int
1193 go !_ !_ Tip = error "Set.findIndex: element is not in the set"
1194 go idx x (Bin _ kx l r) = case compare x kx of
1195 LT -> go idx x l
1196 GT -> go (idx + size l + 1) x r
1197 EQ -> idx + size l
1198 #if __GLASGOW_HASKELL__
1199 {-# INLINABLE findIndex #-}
1200 #endif
1201
1202 -- | /O(log n)/. Lookup the /index/ of an element, which is its zero-based index in
1203 -- the sorted sequence of elements. The index is a number from /0/ up to, but not
1204 -- including, the 'size' of the set.
1205 --
1206 -- > isJust (lookupIndex 2 (fromList [5,3])) == False
1207 -- > fromJust (lookupIndex 3 (fromList [5,3])) == 0
1208 -- > fromJust (lookupIndex 5 (fromList [5,3])) == 1
1209 -- > isJust (lookupIndex 6 (fromList [5,3])) == False
1210 --
1211 -- @since 0.5.4
1212
1213 -- See Note: Type of local 'go' function
1214 lookupIndex :: Ord a => a -> Set a -> Maybe Int
1215 lookupIndex = go 0
1216 where
1217 go :: Ord a => Int -> a -> Set a -> Maybe Int
1218 go !_ !_ Tip = Nothing
1219 go idx x (Bin _ kx l r) = case compare x kx of
1220 LT -> go idx x l
1221 GT -> go (idx + size l + 1) x r
1222 EQ -> Just $! idx + size l
1223 #if __GLASGOW_HASKELL__
1224 {-# INLINABLE lookupIndex #-}
1225 #endif
1226
1227 -- | /O(log n)/. Retrieve an element by its /index/, i.e. by its zero-based
1228 -- index in the sorted sequence of elements. If the /index/ is out of range (less
1229 -- than zero, greater or equal to 'size' of the set), 'error' is called.
1230 --
1231 -- > elemAt 0 (fromList [5,3]) == 3
1232 -- > elemAt 1 (fromList [5,3]) == 5
1233 -- > elemAt 2 (fromList [5,3]) Error: index out of range
1234 --
1235 -- @since 0.5.4
1236
1237 elemAt :: Int -> Set a -> a
1238 elemAt !_ Tip = error "Set.elemAt: index out of range"
1239 elemAt i (Bin _ x l r)
1240 = case compare i sizeL of
1241 LT -> elemAt i l
1242 GT -> elemAt (i-sizeL-1) r
1243 EQ -> x
1244 where
1245 sizeL = size l
1246
1247 -- | /O(log n)/. Delete the element at /index/, i.e. by its zero-based index in
1248 -- the sorted sequence of elements. If the /index/ is out of range (less than zero,
1249 -- greater or equal to 'size' of the set), 'error' is called.
1250 --
1251 -- > deleteAt 0 (fromList [5,3]) == singleton 5
1252 -- > deleteAt 1 (fromList [5,3]) == singleton 3
1253 -- > deleteAt 2 (fromList [5,3]) Error: index out of range
1254 -- > deleteAt (-1) (fromList [5,3]) Error: index out of range
1255 --
1256 -- @since 0.5.4
1257
1258 deleteAt :: Int -> Set a -> Set a
1259 deleteAt !i t =
1260 case t of
1261 Tip -> error "Set.deleteAt: index out of range"
1262 Bin _ x l r -> case compare i sizeL of
1263 LT -> balanceR x (deleteAt i l) r
1264 GT -> balanceL x l (deleteAt (i-sizeL-1) r)
1265 EQ -> glue l r
1266 where
1267 sizeL = size l
1268
1269 -- | Take a given number of elements in order, beginning
1270 -- with the smallest ones.
1271 --
1272 -- @
1273 -- take n = 'fromDistinctAscList' . 'Prelude.take' n . 'toAscList'
1274 -- @
1275 --
1276 -- @since 0.5.8
1277 take :: Int -> Set a -> Set a
1278 take i m | i >= size m = m
1279 take i0 m0 = go i0 m0
1280 where
1281 go i !_ | i <= 0 = Tip
1282 go !_ Tip = Tip
1283 go i (Bin _ x l r) =
1284 case compare i sizeL of
1285 LT -> go i l
1286 GT -> link x l (go (i - sizeL - 1) r)
1287 EQ -> l
1288 where sizeL = size l
1289
1290 -- | Drop a given number of elements in order, beginning
1291 -- with the smallest ones.
1292 --
1293 -- @
1294 -- drop n = 'fromDistinctAscList' . 'Prelude.drop' n . 'toAscList'
1295 -- @
1296 --
1297 -- @since 0.5.8
1298 drop :: Int -> Set a -> Set a
1299 drop i m | i >= size m = Tip
1300 drop i0 m0 = go i0 m0
1301 where
1302 go i m | i <= 0 = m
1303 go !_ Tip = Tip
1304 go i (Bin _ x l r) =
1305 case compare i sizeL of
1306 LT -> link x (go i l) r
1307 GT -> go (i - sizeL - 1) r
1308 EQ -> insertMin x r
1309 where sizeL = size l
1310
1311 -- | /O(log n)/. Split a set at a particular index.
1312 --
1313 -- @
1314 -- splitAt !n !xs = ('take' n xs, 'drop' n xs)
1315 -- @
1316 splitAt :: Int -> Set a -> (Set a, Set a)
1317 splitAt i0 m0
1318 | i0 >= size m0 = (m0, Tip)
1319 | otherwise = toPair $ go i0 m0
1320 where
1321 go i m | i <= 0 = Tip :*: m
1322 go !_ Tip = Tip :*: Tip
1323 go i (Bin _ x l r)
1324 = case compare i sizeL of
1325 LT -> case go i l of
1326 ll :*: lr -> ll :*: link x lr r
1327 GT -> case go (i - sizeL - 1) r of
1328 rl :*: rr -> link x l rl :*: rr
1329 EQ -> l :*: insertMin x r
1330 where sizeL = size l
1331
1332 -- | /O(log n)/. Take while a predicate on the elements holds.
1333 -- The user is responsible for ensuring that for all elements @j@ and @k@ in the set,
1334 -- @j \< k ==\> p j \>= p k@. See note at 'spanAntitone'.
1335 --
1336 -- @
1337 -- takeWhileAntitone p = 'fromDistinctAscList' . 'Data.List.takeWhile' p . 'toList'
1338 -- takeWhileAntitone p = 'filter' p
1339 -- @
1340 --
1341 -- @since 0.5.8
1342
1343 takeWhileAntitone :: (a -> Bool) -> Set a -> Set a
1344 takeWhileAntitone _ Tip = Tip
1345 takeWhileAntitone p (Bin _ x l r)
1346 | p x = link x l (takeWhileAntitone p r)
1347 | otherwise = takeWhileAntitone p l
1348
1349 -- | /O(log n)/. Drop while a predicate on the elements holds.
1350 -- The user is responsible for ensuring that for all elements @j@ and @k@ in the set,
1351 -- @j \< k ==\> p j \>= p k@. See note at 'spanAntitone'.
1352 --
1353 -- @
1354 -- dropWhileAntitone p = 'fromDistinctAscList' . 'Data.List.dropWhile' p . 'toList'
1355 -- dropWhileAntitone p = 'filter' (not . p)
1356 -- @
1357 --
1358 -- @since 0.5.8
1359
1360 dropWhileAntitone :: (a -> Bool) -> Set a -> Set a
1361 dropWhileAntitone _ Tip = Tip
1362 dropWhileAntitone p (Bin _ x l r)
1363 | p x = dropWhileAntitone p r
1364 | otherwise = link x (dropWhileAntitone p l) r
1365
1366 -- | /O(log n)/. Divide a set at the point where a predicate on the elements stops holding.
1367 -- The user is responsible for ensuring that for all elements @j@ and @k@ in the set,
1368 -- @j \< k ==\> p j \>= p k@.
1369 --
1370 -- @
1371 -- spanAntitone p xs = ('takeWhileAntitone' p xs, 'dropWhileAntitone' p xs)
1372 -- spanAntitone p xs = partition p xs
1373 -- @
1374 --
1375 -- Note: if @p@ is not actually antitone, then @spanAntitone@ will split the set
1376 -- at some /unspecified/ point where the predicate switches from holding to not
1377 -- holding (where the predicate is seen to hold before the first element and to fail
1378 -- after the last element).
1379 --
1380 -- @since 0.5.8
1381
1382 spanAntitone :: (a -> Bool) -> Set a -> (Set a, Set a)
1383 spanAntitone p0 m = toPair (go p0 m)
1384 where
1385 go _ Tip = Tip :*: Tip
1386 go p (Bin _ x l r)
1387 | p x = let u :*: v = go p r in link x l u :*: v
1388 | otherwise = let u :*: v = go p l in u :*: link x v r
1389
1390
1391 {--------------------------------------------------------------------
1392 Utility functions that maintain the balance properties of the tree.
1393 All constructors assume that all values in [l] < [x] and all values
1394 in [r] > [x], and that [l] and [r] are valid trees.
1395
1396 In order of sophistication:
1397 [Bin sz x l r] The type constructor.
1398 [bin x l r] Maintains the correct size, assumes that both [l]
1399 and [r] are balanced with respect to each other.
1400 [balance x l r] Restores the balance and size.
1401 Assumes that the original tree was balanced and
1402 that [l] or [r] has changed by at most one element.
1403 [link x l r] Restores balance and size.
1404
1405 Furthermore, we can construct a new tree from two trees. Both operations
1406 assume that all values in [l] < all values in [r] and that [l] and [r]
1407 are valid:
1408 [glue l r] Glues [l] and [r] together. Assumes that [l] and
1409 [r] are already balanced with respect to each other.
1410 [merge l r] Merges two trees and restores balance.
1411 --------------------------------------------------------------------}
1412
1413 {--------------------------------------------------------------------
1414 Link
1415 --------------------------------------------------------------------}
1416 link :: a -> Set a -> Set a -> Set a
1417 link x Tip r = insertMin x r
1418 link x l Tip = insertMax x l
1419 link x l@(Bin sizeL y ly ry) r@(Bin sizeR z lz rz)
1420 | delta*sizeL < sizeR = balanceL z (link x l lz) rz
1421 | delta*sizeR < sizeL = balanceR y ly (link x ry r)
1422 | otherwise = bin x l r
1423
1424
1425 -- insertMin and insertMax don't perform potentially expensive comparisons.
1426 insertMax,insertMin :: a -> Set a -> Set a
1427 insertMax x t
1428 = case t of
1429 Tip -> singleton x
1430 Bin _ y l r
1431 -> balanceR y l (insertMax x r)
1432
1433 insertMin x t
1434 = case t of
1435 Tip -> singleton x
1436 Bin _ y l r
1437 -> balanceL y (insertMin x l) r
1438
1439 {--------------------------------------------------------------------
1440 [merge l r]: merges two trees.
1441 --------------------------------------------------------------------}
1442 merge :: Set a -> Set a -> Set a
1443 merge Tip r = r
1444 merge l Tip = l
1445 merge l@(Bin sizeL x lx rx) r@(Bin sizeR y ly ry)
1446 | delta*sizeL < sizeR = balanceL y (merge l ly) ry
1447 | delta*sizeR < sizeL = balanceR x lx (merge rx r)
1448 | otherwise = glue l r
1449
1450 {--------------------------------------------------------------------
1451 [glue l r]: glues two trees together.
1452 Assumes that [l] and [r] are already balanced with respect to each other.
1453 --------------------------------------------------------------------}
1454 glue :: Set a -> Set a -> Set a
1455 glue Tip r = r
1456 glue l Tip = l
1457 glue l@(Bin sl xl ll lr) r@(Bin sr xr rl rr)
1458 | sl > sr = let !(m :*: l') = maxViewSure xl ll lr in balanceR m l' r
1459 | otherwise = let !(m :*: r') = minViewSure xr rl rr in balanceL m l r'
1460
1461 -- | /O(log n)/. Delete and find the minimal element.
1462 --
1463 -- > deleteFindMin set = (findMin set, deleteMin set)
1464
1465 deleteFindMin :: Set a -> (a,Set a)
1466 deleteFindMin t
1467 | Just r <- minView t = r
1468 | otherwise = (error "Set.deleteFindMin: can not return the minimal element of an empty set", Tip)
1469
1470 -- | /O(log n)/. Delete and find the maximal element.
1471 --
1472 -- > deleteFindMax set = (findMax set, deleteMax set)
1473 deleteFindMax :: Set a -> (a,Set a)
1474 deleteFindMax t
1475 | Just r <- maxView t = r
1476 | otherwise = (error "Set.deleteFindMax: can not return the maximal element of an empty set", Tip)
1477
1478 minViewSure :: a -> Set a -> Set a -> StrictPair a (Set a)
1479 minViewSure = go
1480 where
1481 go x Tip r = x :*: r
1482 go x (Bin _ xl ll lr) r =
1483 case go xl ll lr of
1484 xm :*: l' -> xm :*: balanceR x l' r
1485
1486 -- | /O(log n)/. Retrieves the minimal key of the set, and the set
1487 -- stripped of that element, or 'Nothing' if passed an empty set.
1488 minView :: Set a -> Maybe (a, Set a)
1489 minView Tip = Nothing
1490 minView (Bin _ x l r) = Just $! toPair $ minViewSure x l r
1491
1492 maxViewSure :: a -> Set a -> Set a -> StrictPair a (Set a)
1493 maxViewSure = go
1494 where
1495 go x l Tip = x :*: l
1496 go x l (Bin _ xr rl rr) =
1497 case go xr rl rr of
1498 xm :*: r' -> xm :*: balanceL x l r'
1499
1500 -- | /O(log n)/. Retrieves the maximal key of the set, and the set
1501 -- stripped of that element, or 'Nothing' if passed an empty set.
1502 maxView :: Set a -> Maybe (a, Set a)
1503 maxView Tip = Nothing
1504 maxView (Bin _ x l r) = Just $! toPair $ maxViewSure x l r
1505
1506 {--------------------------------------------------------------------
1507 [balance x l r] balances two trees with value x.
1508 The sizes of the trees should balance after decreasing the
1509 size of one of them. (a rotation).
1510
1511 [delta] is the maximal relative difference between the sizes of
1512 two trees, it corresponds with the [w] in Adams' paper.
1513 [ratio] is the ratio between an outer and inner sibling of the
1514 heavier subtree in an unbalanced setting. It determines
1515 whether a double or single rotation should be performed
1516 to restore balance. It is correspondes with the inverse
1517 of $\alpha$ in Adam's article.
1518
1519 Note that according to the Adam's paper:
1520 - [delta] should be larger than 4.646 with a [ratio] of 2.
1521 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
1522
1523 But the Adam's paper is errorneous:
1524 - it can be proved that for delta=2 and delta>=5 there does
1525 not exist any ratio that would work
1526 - delta=4.5 and ratio=2 does not work
1527
1528 That leaves two reasonable variants, delta=3 and delta=4,
1529 both with ratio=2.
1530
1531 - A lower [delta] leads to a more 'perfectly' balanced tree.
1532 - A higher [delta] performs less rebalancing.
1533
1534 In the benchmarks, delta=3 is faster on insert operations,
1535 and delta=4 has slightly better deletes. As the insert speedup
1536 is larger, we currently use delta=3.
1537
1538 --------------------------------------------------------------------}
1539 delta,ratio :: Int
1540 delta = 3
1541 ratio = 2
1542
1543 -- The balance function is equivalent to the following:
1544 --
1545 -- balance :: a -> Set a -> Set a -> Set a
1546 -- balance x l r
1547 -- | sizeL + sizeR <= 1 = Bin sizeX x l r
1548 -- | sizeR > delta*sizeL = rotateL x l r
1549 -- | sizeL > delta*sizeR = rotateR x l r
1550 -- | otherwise = Bin sizeX x l r
1551 -- where
1552 -- sizeL = size l
1553 -- sizeR = size r
1554 -- sizeX = sizeL + sizeR + 1
1555 --
1556 -- rotateL :: a -> Set a -> Set a -> Set a
1557 -- rotateL x l r@(Bin _ _ ly ry) | size ly < ratio*size ry = singleL x l r
1558 -- | otherwise = doubleL x l r
1559 -- rotateR :: a -> Set a -> Set a -> Set a
1560 -- rotateR x l@(Bin _ _ ly ry) r | size ry < ratio*size ly = singleR x l r
1561 -- | otherwise = doubleR x l r
1562 --
1563 -- singleL, singleR :: a -> Set a -> Set a -> Set a
1564 -- singleL x1 t1 (Bin _ x2 t2 t3) = bin x2 (bin x1 t1 t2) t3
1565 -- singleR x1 (Bin _ x2 t1 t2) t3 = bin x2 t1 (bin x1 t2 t3)
1566 --
1567 -- doubleL, doubleR :: a -> Set a -> Set a -> Set a
1568 -- doubleL x1 t1 (Bin _ x2 (Bin _ x3 t2 t3) t4) = bin x3 (bin x1 t1 t2) (bin x2 t3 t4)
1569 -- doubleR x1 (Bin _ x2 t1 (Bin _ x3 t2 t3)) t4 = bin x3 (bin x2 t1 t2) (bin x1 t3 t4)
1570 --
1571 -- It is only written in such a way that every node is pattern-matched only once.
1572 --
1573 -- Only balanceL and balanceR are needed at the moment, so balance is not here anymore.
1574 -- In case it is needed, it can be found in Data.Map.
1575
1576 -- Functions balanceL and balanceR are specialised versions of balance.
1577 -- balanceL only checks whether the left subtree is too big,
1578 -- balanceR only checks whether the right subtree is too big.
1579
1580 -- balanceL is called when left subtree might have been inserted to or when
1581 -- right subtree might have been deleted from.
1582 balanceL :: a -> Set a -> Set a -> Set a
1583 balanceL x l r = case r of
1584 Tip -> case l of
1585 Tip -> Bin 1 x Tip Tip
1586 (Bin _ _ Tip Tip) -> Bin 2 x l Tip
1587 (Bin _ lx Tip (Bin _ lrx _ _)) -> Bin 3 lrx (Bin 1 lx Tip Tip) (Bin 1 x Tip Tip)
1588 (Bin _ lx ll@(Bin _ _ _ _) Tip) -> Bin 3 lx ll (Bin 1 x Tip Tip)
1589 (Bin ls lx ll@(Bin lls _ _ _) lr@(Bin lrs lrx lrl lrr))
1590 | lrs < ratio*lls -> Bin (1+ls) lx ll (Bin (1+lrs) x lr Tip)
1591 | otherwise -> Bin (1+ls) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+size lrr) x lrr Tip)
1592
1593 (Bin rs _ _ _) -> case l of
1594 Tip -> Bin (1+rs) x Tip r
1595
1596 (Bin ls lx ll lr)
1597 | ls > delta*rs -> case (ll, lr) of
1598 (Bin lls _ _ _, Bin lrs lrx lrl lrr)
1599 | lrs < ratio*lls -> Bin (1+ls+rs) lx ll (Bin (1+rs+lrs) x lr r)
1600 | otherwise -> Bin (1+ls+rs) lrx (Bin (1+lls+size lrl) lx ll lrl) (Bin (1+rs+size lrr) x lrr r)
1601 (_, _) -> error "Failure in Data.Map.balanceL"
1602 | otherwise -> Bin (1+ls+rs) x l r
1603 {-# NOINLINE balanceL #-}
1604
1605 -- balanceR is called when right subtree might have been inserted to or when
1606 -- left subtree might have been deleted from.
1607 balanceR :: a -> Set a -> Set a -> Set a
1608 balanceR x l r = case l of
1609 Tip -> case r of
1610 Tip -> Bin 1 x Tip Tip
1611 (Bin _ _ Tip Tip) -> Bin 2 x Tip r
1612 (Bin _ rx Tip rr@(Bin _ _ _ _)) -> Bin 3 rx (Bin 1 x Tip Tip) rr
1613 (Bin _ rx (Bin _ rlx _ _) Tip) -> Bin 3 rlx (Bin 1 x Tip Tip) (Bin 1 rx Tip Tip)
1614 (Bin rs rx rl@(Bin rls rlx rll rlr) rr@(Bin rrs _ _ _))
1615 | rls < ratio*rrs -> Bin (1+rs) rx (Bin (1+rls) x Tip rl) rr
1616 | otherwise -> Bin (1+rs) rlx (Bin (1+size rll) x Tip rll) (Bin (1+rrs+size rlr) rx rlr rr)
1617
1618 (Bin ls _ _ _) -> case r of
1619 Tip -> Bin (1+ls) x l Tip
1620
1621 (Bin rs rx rl rr)
1622 | rs > delta*ls -> case (rl, rr) of
1623 (Bin rls rlx rll rlr, Bin rrs _ _ _)
1624 | rls < ratio*rrs -> Bin (1+ls+rs) rx (Bin (1+ls+rls) x l rl) rr
1625 | otherwise -> Bin (1+ls+rs) rlx (Bin (1+ls+size rll) x l rll) (Bin (1+rrs+size rlr) rx rlr rr)
1626 (_, _) -> error "Failure in Data.Map.balanceR"
1627 | otherwise -> Bin (1+ls+rs) x l r
1628 {-# NOINLINE balanceR #-}
1629
1630 {--------------------------------------------------------------------
1631 The bin constructor maintains the size of the tree
1632 --------------------------------------------------------------------}
1633 bin :: a -> Set a -> Set a -> Set a
1634 bin x l r
1635 = Bin (size l + size r + 1) x l r
1636 {-# INLINE bin #-}
1637
1638
1639 {--------------------------------------------------------------------
1640 Utilities
1641 --------------------------------------------------------------------}
1642
1643 -- | /O(1)/. Decompose a set into pieces based on the structure of the underlying
1644 -- tree. This function is useful for consuming a set in parallel.
1645 --
1646 -- No guarantee is made as to the sizes of the pieces; an internal, but
1647 -- deterministic process determines this. However, it is guaranteed that the pieces
1648 -- returned will be in ascending order (all elements in the first subset less than all
1649 -- elements in the second, and so on).
1650 --
1651 -- Examples:
1652 --
1653 -- > splitRoot (fromList [1..6]) ==
1654 -- > [fromList [1,2,3],fromList [4],fromList [5,6]]
1655 --
1656 -- > splitRoot empty == []
1657 --
1658 -- Note that the current implementation does not return more than three subsets,
1659 -- but you should not depend on this behaviour because it can change in the
1660 -- future without notice.
1661 --
1662 -- @since 0.5.4
1663 splitRoot :: Set a -> [Set a]
1664 splitRoot orig =
1665 case orig of
1666 Tip -> []
1667 Bin _ v l r -> [l, singleton v, r]
1668 {-# INLINE splitRoot #-}
1669
1670
1671 -- | Calculate the power set of a set: the set of all its subsets.
1672 --
1673 -- @
1674 -- t `member` powerSet s == t `isSubsetOf` s
1675 -- @
1676 --
1677 -- Example:
1678 --
1679 -- @
1680 -- powerSet (fromList [1,2,3]) =
1681 -- fromList [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
1682 -- @
1683 --
1684 -- @since 0.5.11
1685 powerSet :: Set a -> Set (Set a)
1686 powerSet xs0 = insertMin empty (foldr' step Tip xs0) where
1687 step x pxs = insertMin (singleton x) (insertMin x `mapMonotonic` pxs) `glue` pxs
1688
1689 -- | Calculate the Cartesian product of two sets.
1690 --
1691 -- @
1692 -- cartesianProduct xs ys = fromList $ liftA2 (,) (toList xs) (toList ys)
1693 -- @
1694 --
1695 -- Example:
1696 --
1697 -- @
1698 -- cartesianProduct (fromList [1,2]) (fromList ['a','b']) =
1699 -- fromList [(1,'a'), (1,'b'), (2,'a'), (2,'b')]
1700 -- @
1701 --
1702 -- @since 0.5.11
1703 cartesianProduct :: Set a -> Set b -> Set (a, b)
1704 cartesianProduct as bs =
1705 getMergeSet $ foldMap (\a -> MergeSet $ mapMonotonic ((,) a) bs) as
1706
1707 -- A version of Set with peculiar Semigroup and Monoid instances.
1708 -- The result of xs <> ys will only be a valid set if the greatest
1709 -- element of xs is strictly less than the least element of ys.
1710 -- This is used to define cartesianProduct.
1711 newtype MergeSet a = MergeSet { getMergeSet :: Set a }
1712
1713 #if (MIN_VERSION_base(4,9,0))
1714 instance Semigroup (MergeSet a) where
1715 MergeSet xs <> MergeSet ys = MergeSet (merge xs ys)
1716 #endif
1717
1718 instance Monoid (MergeSet a) where
1719 mempty = MergeSet empty
1720
1721 #if (MIN_VERSION_base(4,9,0))
1722 mappend = (<>)
1723 #else
1724 mappend (MergeSet xs) (MergeSet ys) = MergeSet (merge xs ys)
1725 #endif
1726
1727 -- | Calculate the disjoin union of two sets.
1728 --
1729 -- @ disjointUnion xs ys = map Left xs `union` map Right ys @
1730 --
1731 -- Example:
1732 --
1733 -- @
1734 -- disjointUnion (fromList [1,2]) (fromList ["hi", "bye"]) =
1735 -- fromList [Left 1, Left 2, Right "hi", Right "bye"]
1736 -- @
1737 --
1738 -- @since 0.5.11
1739 disjointUnion :: Set a -> Set b -> Set (Either a b)
1740 disjointUnion as bs = merge (mapMonotonic Left as) (mapMonotonic Right bs)
1741
1742 {--------------------------------------------------------------------
1743 Debugging
1744 --------------------------------------------------------------------}
1745 -- | /O(n)/. Show the tree that implements the set. The tree is shown
1746 -- in a compressed, hanging format.
1747 showTree :: Show a => Set a -> String
1748 showTree s
1749 = showTreeWith True False s
1750
1751
1752 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
1753 the tree that implements the set. If @hang@ is
1754 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
1755 @wide@ is 'True', an extra wide version is shown.
1756
1757 > Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5]
1758 > 4
1759 > +--2
1760 > | +--1
1761 > | +--3
1762 > +--5
1763 >
1764 > Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5]
1765 > 4
1766 > |
1767 > +--2
1768 > | |
1769 > | +--1
1770 > | |
1771 > | +--3
1772 > |
1773 > +--5
1774 >
1775 > Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5]
1776 > +--5
1777 > |
1778 > 4
1779 > |
1780 > | +--3
1781 > | |
1782 > +--2
1783 > |
1784 > +--1
1785
1786 -}
1787 showTreeWith :: Show a => Bool -> Bool -> Set a -> String
1788 showTreeWith hang wide t
1789 | hang = (showsTreeHang wide [] t) ""
1790 | otherwise = (showsTree wide [] [] t) ""
1791
1792 showsTree :: Show a => Bool -> [String] -> [String] -> Set a -> ShowS
1793 showsTree wide lbars rbars t
1794 = case t of
1795 Tip -> showsBars lbars . showString "|\n"
1796 Bin _ x Tip Tip
1797 -> showsBars lbars . shows x . showString "\n"
1798 Bin _ x l r
1799 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
1800 showWide wide rbars .
1801 showsBars lbars . shows x . showString "\n" .
1802 showWide wide lbars .
1803 showsTree wide (withEmpty lbars) (withBar lbars) l
1804
1805 showsTreeHang :: Show a => Bool -> [String] -> Set a -> ShowS
1806 showsTreeHang wide bars t
1807 = case t of
1808 Tip -> showsBars bars . showString "|\n"
1809 Bin _ x Tip Tip
1810 -> showsBars bars . shows x . showString "\n"
1811 Bin _ x l r
1812 -> showsBars bars . shows x . showString "\n" .
1813 showWide wide bars .
1814 showsTreeHang wide (withBar bars) l .
1815 showWide wide bars .
1816 showsTreeHang wide (withEmpty bars) r
1817
1818 showWide :: Bool -> [String] -> String -> String
1819 showWide wide bars
1820 | wide = showString (concat (reverse bars)) . showString "|\n"
1821 | otherwise = id
1822
1823 showsBars :: [String] -> ShowS
1824 showsBars bars
1825 = case bars of
1826 [] -> id
1827 _ -> showString (concat (reverse (tail bars))) . showString node
1828
1829 node :: String
1830 node = "+--"
1831
1832 withBar, withEmpty :: [String] -> [String]
1833 withBar bars = "| ":bars
1834 withEmpty bars = " ":bars
1835
1836 {--------------------------------------------------------------------
1837 Assertions
1838 --------------------------------------------------------------------}
1839 -- | /O(n)/. Test if the internal set structure is valid.
1840 valid :: Ord a => Set a -> Bool
1841 valid t
1842 = balanced t && ordered t && validsize t
1843
1844 ordered :: Ord a => Set a -> Bool
1845 ordered t
1846 = bounded (const True) (const True) t
1847 where
1848 bounded lo hi t'
1849 = case t' of
1850 Tip -> True
1851 Bin _ x l r -> (lo x) && (hi x) && bounded lo (<x) l && bounded (>x) hi r
1852
1853 balanced :: Set a -> Bool
1854 balanced t
1855 = case t of
1856 Tip -> True
1857 Bin _ _ l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1858 balanced l && balanced r
1859
1860 validsize :: Set a -> Bool
1861 validsize t
1862 = (realsize t == Just (size t))
1863 where
1864 realsize t'
1865 = case t' of
1866 Tip -> Just 0
1867 Bin sz _ l r -> case (realsize l,realsize r) of
1868 (Just n,Just m) | n+m+1 == sz -> Just sz
1869 _ -> Nothing