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