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