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