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