-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathInternal.hs
More file actions
2239 lines (1983 loc) · 74.8 KB
/
Copy pathInternal.hs
File metadata and controls
2239 lines (1983 loc) · 74.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
#ifdef __GLASGOW_HASKELL__
{-# LANGUAGE DeriveLift #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE Trustworthy #-}
#endif
{-# OPTIONS_HADDOCK not-home #-}
#include "containers.h"
-----------------------------------------------------------------------------
-- |
-- Module : Data.IntSet.Internal
-- Copyright : (c) Daan Leijen 2002
-- (c) Joachim Breitner 2011
-- License : BSD-style
-- Maintainer : libraries@haskell.org
-- Portability : portable
--
-- = WARNING
--
-- This module is considered __internal__.
--
-- The Package Versioning Policy __does not apply__.
--
-- The contents of this module may change __in any way whatsoever__
-- and __without any warning__ between minor versions of this package.
--
-- Authors importing this module are expected to track development
-- closely.
--
--
-- = Finite Int Sets (internals)
--
-- The @'IntSet'@ type represents a set of elements of type @Int@. An @IntSet@
-- is strict in its elements.
--
--
-- == Implementation
--
-- The implementation is based on /big-endian patricia trees/. This data
-- structure performs especially well on binary operations like 'union'
-- and 'intersection'. Additionally, benchmarks show that it is also
-- (much) faster on insertions and deletions when compared to a generic
-- size-balanced set implementation (see "Data.Set").
--
-- * Chris Okasaki and Andy Gill,
-- \"/Fast Mergeable Integer Maps/\",
-- Workshop on ML, September 1998, pages 77-86,
-- <https://web.archive.org/web/20150417234429/https://ittc.ku.edu/~andygill/papers/IntMap98.pdf>.
--
-- * D.R. Morrison,
-- \"/PATRICIA -- Practical Algorithm To Retrieve Information Coded In Alphanumeric/\",
-- Journal of the ACM, 15(4), October 1968, pages 514-534,
-- <https://doi.org/10.1145/321479.321481>.
--
-- Additionally, this implementation places bitmaps in the leaves of the tree.
-- Their size is the natural size of a machine word (32 or 64 bits) and greatly
-- reduces the memory footprint and execution times for dense sets, e.g. sets
-- where it is likely that many values lie close to each other. The asymptotics
-- are not affected by this optimization.
--
-- @since 0.5.9
-----------------------------------------------------------------------------
-- [Note: Local 'go' functions and capturing]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Care must be taken when using 'go' function which captures an argument.
-- Sometimes (for example when the argument is passed to a data constructor,
-- as in insert), GHC heap-allocates more than necessary. Therefore C-- code
-- must be checked for increased allocation when creating and modifying such
-- functions.
-- [Note: Order of constructors]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The order of constructors of IntSet matters when considering performance.
-- Currently in GHC 7.0, when type has 3 constructors, they are matched from
-- the first to the last -- the best performance is achieved when the
-- constructors are ordered by frequency.
-- On GHC 7.0, reordering constructors from Nil | Tip | Bin to Bin | Tip | Nil
-- improves the benchmark by circa 10%.
module Data.IntSet.Internal (
-- * Set type
IntSet(..) -- instance Eq,Show
, Key
, BitMap
-- * Operators
, (\\)
-- * Query
, null
, size
, compareSize
, member
, notMember
, lookupLT
, lookupGT
, lookupLE
, lookupGE
, isSubsetOf
, isProperSubsetOf
, disjoint
-- * Construction
, empty
, singleton
, fromRange
, insert
, delete
, pop
, alterF
-- * Combine
, union
, unions
, difference
, intersection
, intersections
, symmetricDifference
, Intersection(..)
-- * Filter
, filter
, partition
, takeWhileAntitone
, dropWhileAntitone
, spanAntitone
, mapMaybe
, split
, splitMember
, splitRoot
-- * Map
, map
, mapMonotonic
-- * Folds
, foldr
, foldl
, foldMap
-- ** Strict folds
, foldr'
, foldl'
-- ** Legacy folds
, fold
-- * Min\/Max
, lookupMin
, lookupMax
, findMin
, findMax
, deleteMin
, deleteMax
, deleteFindMin
, deleteFindMax
, maxView
, minView
-- * Conversion
-- ** List
, elems
, toList
, fromList
-- ** Ordered list
, toAscList
, toDescList
, fromAscList
, fromDistinctAscList
, fromDescList
-- * Debugging
, showTree
, showTreeWith
-- * Internals
, suffixBitMask
, prefixBitMask
, prefixOf
, suffixOf
, bitmapOf
) where
import Control.Applicative (Const(..))
import Control.DeepSeq (NFData(rnf))
import Data.Bits
import qualified Data.List as List
import Data.List.NonEmpty (NonEmpty(..))
import Data.Maybe (fromMaybe)
import Data.Semigroup (Semigroup(..), stimesIdempotent, stimesIdempotentMonoid)
import Utils.Containers.Internal.Prelude hiding
(filter, foldr, foldl, foldl', foldMap, null, map)
import Prelude ()
import Utils.Containers.Internal.BitUtil (iShiftRL, shiftLL, shiftRL)
import Utils.Containers.Internal.Strict
(StrictPair(..), StrictTriple(..), toPair)
import Data.IntSet.Internal.IntTreeCommons
( Key
, Prefix(..)
, nomatch
, left
, signBranch
, mask
, branchMask
, branchPrefix
, TreeTreeBranch(..)
, treeTreeBranch
, i2w
, Order(..)
)
#if __GLASGOW_HASKELL__
import Data.Data (Data(..), Constr, mkConstr, constrIndex, DataType, mkDataType)
import qualified Data.Data
import Text.Read
import Data.Coerce (coerce)
#endif
#if __GLASGOW_HASKELL__
import qualified GHC.Exts
# if __GLASGOW_HASKELL__ >= 914
import Language.Haskell.TH.Lift (Lift)
# else
import Language.Haskell.TH.Syntax (Lift)
-- See Note [ Template Haskell Dependencies ]
import Language.Haskell.TH ()
# endif
#endif
import qualified Data.Foldable as Foldable
infixl 9 \\{-This comment teaches CPP correct behaviour -}
{--------------------------------------------------------------------
Operators
--------------------------------------------------------------------}
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- See 'difference'.
(\\) :: IntSet -> IntSet -> IntSet
m1 \\ m2 = difference m1 m2
{--------------------------------------------------------------------
Types
--------------------------------------------------------------------}
-- | A set of integers.
-- See Note: Order of constructors
data IntSet = Bin {-# UNPACK #-} !Prefix
!IntSet
!IntSet
| Tip {-# UNPACK #-} !Int
{-# UNPACK #-} !BitMap
| Nil
type BitMap = Word
--
-- Note [IntSet structure and invariants]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- * Nil is never found as a child of Bin.
--
-- * The Prefix of a Bin indicates the common high-order bits that all keys in
-- the Bin share.
--
-- * The least significant set bit of the Int value of a Prefix is called the
-- mask bit.
--
-- * All the bits to the left of the mask bit are called the shared prefix. All
-- keys stored in the Bin begin with the shared prefix.
--
-- * All keys in the left child of the Bin have the mask bit unset, and all keys
-- in the right child have the mask bit set. It follows that
--
-- 1. The Int value of the Prefix of a Bin is the smallest key that can be
-- present in the right child of the Bin.
--
-- 2. All keys in the right child of a Bin are greater than keys in the
-- left child, with one exceptional situation. If the Bin separates
-- negative and non-negative keys, the mask bit is the sign bit and the
-- left child stores the non-negative keys while the right child stores the
-- negative keys.
--
-- * All bits to the right of the mask bit are set to 0 in a Prefix.
--
-- * The shared prefix of a Bin is never longer than
-- (WORD_SIZE - lg(WORD_SIZE) - 1) bits.
--
-- * In the context of a Tip, the highest (WORD_SIZE - lg(WORD_SIZE)) bits of
-- a key are called "prefix" and the lowest lg(WORD_SIZE) bits are called
-- "suffix". In Tip kx bm, kx is the shared prefix and bm is a bitmask of the
-- suffixes of the keys. In other words, the keys of Tip kx bm are (kx .|. i)
-- for every set bit i in bm.
--
-- * In Tip kx _, the lowest lg(WORD_SIZE) bits of kx are set to 0.
--
-- * In Tip _ bm, bm is never 0.
--
#ifdef __GLASGOW_HASKELL__
-- | @since 0.6.6
deriving instance Lift IntSet
#endif
-- | @mempty@ = 'empty'
instance Monoid IntSet where
mempty = empty
mconcat = unions
#if !MIN_VERSION_base(4,11,0)
mappend = (<>)
#endif
-- | @(<>)@ = 'union'
--
-- @since 0.5.7
instance Semigroup IntSet where
(<>) = union
stimes = stimesIdempotentMonoid
#if __GLASGOW_HASKELL__
{--------------------------------------------------------------------
A Data instance
--------------------------------------------------------------------}
-- This instance preserves data abstraction at the cost of inefficiency.
-- We provide limited reflection services for the sake of data abstraction.
instance Data IntSet where
gfoldl f z is = z fromList `f` (toList is)
toConstr _ = fromListConstr
gunfold k z c = case constrIndex c of
1 -> k (z fromList)
_ -> error "gunfold"
dataTypeOf _ = intSetDataType
fromListConstr :: Constr
fromListConstr = mkConstr intSetDataType "fromList" [] Data.Data.Prefix
intSetDataType :: DataType
intSetDataType = mkDataType "Data.IntSet.Internal.IntSet" [fromListConstr]
#endif
{--------------------------------------------------------------------
Query
--------------------------------------------------------------------}
-- | \(O(1)\). Is the set empty?
null :: IntSet -> Bool
null Nil = True
null _ = False
{-# INLINE null #-}
-- | \(O(n)\). Cardinality of the set.
--
-- __Note__: Unlike @Data.Set.'Data.Set.size'@, this is /not/ \(O(1)\).
--
-- See also: 'compareSize'
size :: IntSet -> Int
size = go 0
where
go !acc (Bin _ l r) = go (go acc l) r
go acc (Tip _ bm) = acc + popCount bm
go acc Nil = acc
-- | \(O(\min(n,c))\). Compare the number of elements in the set to an @Int@.
--
-- @compareSize m c@ returns the same result as @compare ('size' m) c@ but is
-- more efficient when @c@ is smaller than the size of the set.
--
-- @since 0.8.1
compareSize :: IntSet -> Int -> Ordering
compareSize Nil c0 = compare 0 c0
compareSize _ c0 | c0 <= 0 = GT
compareSize t c0 = compare 0 (go t (c0 - 1))
where
go (Bin _ _ _) 0 = -1
go (Bin _ l r) c
| c' < 0 = c'
| otherwise = go r c'
where
c' = go l (c - 1)
go (Tip _ bm) c = c + 1 - popCount bm
go Nil !_ = error "compareSize.go: Nil"
-- | \(O(\min(n,W))\). Is the value a member of the set?
-- See Note: Local 'go' functions and capturing.
member :: Key -> IntSet -> Bool
member !x = go
where
go (Bin p l r)
| nomatch x p = False
| left x p = go l
| otherwise = go r
go (Tip y bm) = prefixOf x == y && bitmapOf x .&. bm /= 0
go Nil = False
-- | \(O(\min(n,W))\). Is the element not in the set?
notMember :: Key -> IntSet -> Bool
notMember k = not . member k
-- | \(O(\min(n,W))\). Find largest element smaller than the given one.
--
-- > lookupLT 3 (fromList [3, 5]) == Nothing
-- > lookupLT 5 (fromList [3, 5]) == Just 3
-- See Note: Local 'go' functions and capturing.
lookupLT :: Key -> IntSet -> Maybe Key
lookupLT !x t = case t of
Bin p l r | signBranch p -> if x >= 0 then go r l else go Nil r
_ -> go Nil t
where
go def (Bin p l r) | nomatch x p = if x < unPrefix p then unsafeFindMax def else unsafeFindMax r
| left x p = go def l
| otherwise = go l r
go def (Tip kx bm) | prefixOf x > kx = Just $ kx + highestBitSet bm
| prefixOf x == kx && maskLT /= 0 = Just $ kx + highestBitSet maskLT
| otherwise = unsafeFindMax def
where maskLT = (bitmapOf x - 1) .&. bm
go def Nil = unsafeFindMax def
-- | \(O(\min(n,W))\). Find smallest element greater than the given one.
--
-- > lookupGT 4 (fromList [3, 5]) == Just 5
-- > lookupGT 5 (fromList [3, 5]) == Nothing
-- See Note: Local 'go' functions and capturing.
lookupGT :: Key -> IntSet -> Maybe Key
lookupGT !x t = case t of
Bin p l r | signBranch p -> if x >= 0 then go Nil l else go l r
_ -> go Nil t
where
go def (Bin p l r) | nomatch x p = if x < unPrefix p then unsafeFindMin l else unsafeFindMin def
| left x p = go r l
| otherwise = go def r
go def (Tip kx bm) | prefixOf x < kx = Just $ kx + lowestBitSet bm
| prefixOf x == kx && maskGT /= 0 = Just $ kx + lowestBitSet maskGT
| otherwise = unsafeFindMin def
where maskGT = (- ((bitmapOf x) `shiftLL` 1)) .&. bm
go def Nil = unsafeFindMin def
-- | \(O(\min(n,W))\). Find largest element smaller or equal to the given one.
--
-- > lookupLE 2 (fromList [3, 5]) == Nothing
-- > lookupLE 4 (fromList [3, 5]) == Just 3
-- > lookupLE 5 (fromList [3, 5]) == Just 5
-- See Note: Local 'go' functions and capturing.
lookupLE :: Key -> IntSet -> Maybe Key
lookupLE !x t = case t of
Bin p l r | signBranch p -> if x >= 0 then go r l else go Nil r
_ -> go Nil t
where
go def (Bin p l r) | nomatch x p = if x < unPrefix p then unsafeFindMax def else unsafeFindMax r
| left x p = go def l
| otherwise = go l r
go def (Tip kx bm) | prefixOf x > kx = Just $ kx + highestBitSet bm
| prefixOf x == kx && maskLE /= 0 = Just $ kx + highestBitSet maskLE
| otherwise = unsafeFindMax def
where maskLE = (((bitmapOf x) `shiftLL` 1) - 1) .&. bm
go def Nil = unsafeFindMax def
-- | \(O(\min(n,W))\). Find smallest element greater or equal to the given one.
--
-- > lookupGE 3 (fromList [3, 5]) == Just 3
-- > lookupGE 4 (fromList [3, 5]) == Just 5
-- > lookupGE 6 (fromList [3, 5]) == Nothing
-- See Note: Local 'go' functions and capturing.
lookupGE :: Key -> IntSet -> Maybe Key
lookupGE !x t = case t of
Bin p l r | signBranch p -> if x >= 0 then go Nil l else go l r
_ -> go Nil t
where
go def (Bin p l r) | nomatch x p = if x < unPrefix p then unsafeFindMin l else unsafeFindMin def
| left x p = go r l
| otherwise = go def r
go def (Tip kx bm) | prefixOf x < kx = Just $ kx + lowestBitSet bm
| prefixOf x == kx && maskGE /= 0 = Just $ kx + lowestBitSet maskGE
| otherwise = unsafeFindMin def
where maskGE = (- (bitmapOf x)) .&. bm
go def Nil = unsafeFindMin def
-- Helper function for lookupGE and lookupGT. It assumes that if a Bin node is
-- given, it has m > 0.
unsafeFindMin :: IntSet -> Maybe Key
unsafeFindMin Nil = Nothing
unsafeFindMin (Tip kx bm) = Just $ kx + lowestBitSet bm
unsafeFindMin (Bin _ l _) = unsafeFindMin l
-- Helper function for lookupLE and lookupLT. It assumes that if a Bin node is
-- given, it has m > 0.
unsafeFindMax :: IntSet -> Maybe Key
unsafeFindMax Nil = Nothing
unsafeFindMax (Tip kx bm) = Just $ kx + highestBitSet bm
unsafeFindMax (Bin _ _ r) = unsafeFindMax r
{--------------------------------------------------------------------
Construction
--------------------------------------------------------------------}
-- | \(O(1)\). The empty set.
empty :: IntSet
empty
= Nil
{-# INLINE empty #-}
-- | \(O(1)\). A set of one element.
singleton :: Key -> IntSet
singleton x
= Tip (prefixOf x) (bitmapOf x)
{-# INLINE singleton #-}
{--------------------------------------------------------------------
Insert
--------------------------------------------------------------------}
-- | \(O(\min(n,W))\). Add a value to the set.
insert :: Key -> IntSet -> IntSet
insert !x = insertBM (prefixOf x) (bitmapOf x)
-- Helper function for insert and union.
insertBM :: Int -> BitMap -> IntSet -> IntSet
insertBM !kx !bm t@(Bin p l r)
| nomatch kx p = linkKey kx (Tip kx bm) p t
| left kx p = Bin p (insertBM kx bm l) r
| otherwise = Bin p l (insertBM kx bm r)
insertBM kx bm t@(Tip kx' bm')
| kx' == kx = Tip kx' (bm .|. bm')
| otherwise = link kx (Tip kx bm) kx' t
insertBM kx bm Nil = Tip kx bm
-- | \(O(\min(n,W))\). Delete a value in the set. Returns the
-- original set when the value was not present.
delete :: Key -> IntSet -> IntSet
delete !x = deleteBM (prefixOf x) (bitmapOf x)
-- Deletes all values mentioned in the BitMap from the set.
-- Helper function for delete and difference.
deleteBM :: Int -> BitMap -> IntSet -> IntSet
deleteBM !kx !bm t@(Bin p l r)
| nomatch kx p = t
| left kx p = binCheckL p (deleteBM kx bm l) r
| otherwise = binCheckR p l (deleteBM kx bm r)
deleteBM kx bm t@(Tip kx' bm')
| kx' == kx = tip kx (bm' .&. complement bm)
| otherwise = t
deleteBM _ _ Nil = Nil
-- | \(O(\min(n,W))\). Pop an element from the set.
--
-- Returns @Nothing@ if the element is not a member of the set. Otherwise
-- returns @Just@ the set with the element removed.
--
-- @
-- pop 1 (fromList [0,2,4]) == Nothing
-- pop 2 (fromList [0,2,4]) == Just (fromList [0,4])
-- @
--
-- @since 0.8.1
pop :: Key -> IntSet -> Maybe IntSet
pop x0 t0 = case go x0 t0 of
True :*: t -> Just t
_ -> Nothing
where
-- We use `StrictPair Bool IntSet` instead of a sum to avoid allocations.
-- See Note [Popped impl] in Data.Map.Internal
go !x (Bin p l r)
| nomatch x p = False :*: Nil
| left x p = case go x l of
True :*: l' -> True :*: binCheckL p l' r
q -> q
| otherwise = case go x r of
True :*: r' -> True :*: binCheckR p l r'
q -> q
go !x (Tip ky bmy)
| prefixOf x == ky && bmx .&. bmy /= 0 = True :*: tip ky (bmx `xor` bmy)
| otherwise = False :*: Nil
where
bmx = bitmapOf x
go !_ Nil = False :*: Nil
-- | \(O(\min(n,W))\). @('alterF' f x s)@ can delete or insert @x@ in @s@ depending
-- on whether it is already present in @s@.
--
-- In short:
--
-- @
-- 'member' x \<$\> 'alterF' f x s = f ('member' x s)
-- @
--
-- Note: 'alterF' is a variant of the @at@ combinator from "Control.Lens.At".
--
-- === Examples
--
-- @
-- -- Get whether the element is a member, and also insert or remove it.
-- getAndSet :: Key -> Bool -> IntSet -> (Bool, IntSet)
-- getAndSet x new = alterF (\\old -> (old, new)) x
-- @
--
-- @
-- -- Delete the element. If it is absent the result is Nothing.
-- mustDelete :: Key -> IntSet -> Maybe IntSet
-- mustDelete = alterF (\\b -> if b then Just False else Nothing)
-- @
--
-- @since 0.6.3.1
alterF :: Functor f => (Bool -> f Bool) -> Key -> IntSet -> f IntSet
alterF f k s = fmap choose (f member_)
where
member_ = member k s
inserted = if member_ then s else insert k s
deleted = if member_ then delete k s else s
choose True = inserted
choose False = deleted
#ifdef __GLASGOW_HASKELL__
{-# INLINE [2] alterF #-}
{-# RULES
"alterF/Const" forall k (f :: Bool -> Const a Bool) . alterF f k = \s -> Const . getConst . f $ member k s
#-}
#endif
{--------------------------------------------------------------------
Union
--------------------------------------------------------------------}
-- | The union of a list of sets.
unions :: Foldable f => f IntSet -> IntSet
unions xs
= Foldable.foldl' union empty xs
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- The union of two sets.
union :: IntSet -> IntSet -> IntSet
union t1@(Bin p1 l1 r1) t2@(Bin p2 l2 r2) = case treeTreeBranch p1 p2 of
ABL -> Bin p1 (union l1 t2) r1
ABR -> Bin p1 l1 (union r1 t2)
BAL -> Bin p2 (union t1 l2) r2
BAR -> Bin p2 l2 (union t1 r2)
EQL -> Bin p1 (union l1 l2) (union r1 r2)
NOM -> link (unPrefix p1) t1 (unPrefix p2) t2
union t@(Bin _ _ _) (Tip kx bm) = insertBM kx bm t
union t@(Bin _ _ _) Nil = t
union (Tip kx bm) t = insertBM kx bm t
union Nil t = t
{--------------------------------------------------------------------
Difference
--------------------------------------------------------------------}
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- Difference between two sets.
difference :: IntSet -> IntSet -> IntSet
difference t1@(Bin p1 l1 r1) t2@(Bin p2 l2 r2) = case treeTreeBranch p1 p2 of
ABL -> binCheckL p1 (difference l1 t2) r1
ABR -> binCheckR p1 l1 (difference r1 t2)
BAL -> difference t1 l2
BAR -> difference t1 r2
EQL -> bin p1 (difference l1 l2) (difference r1 r2)
NOM -> t1
difference t@(Bin _ _ _) (Tip kx bm) = deleteBM kx bm t
difference t@(Bin _ _ _) Nil = t
difference t1@(Tip kx bm) t2 = differenceTip t2
where differenceTip (Bin p2 l2 r2) | nomatch kx p2 = t1
| left kx p2 = differenceTip l2
| otherwise = differenceTip r2
differenceTip (Tip kx2 bm2) | kx == kx2 = tip kx (bm .&. complement bm2)
| otherwise = t1
differenceTip Nil = t1
difference Nil _ = Nil
{--------------------------------------------------------------------
Intersection
--------------------------------------------------------------------}
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- The intersection of two sets.
intersection :: IntSet -> IntSet -> IntSet
intersection t1@(Bin p1 l1 r1) t2@(Bin p2 l2 r2) = case treeTreeBranch p1 p2 of
ABL -> intersection l1 t2
ABR -> intersection r1 t2
BAL -> intersection t1 l2
BAR -> intersection t1 r2
EQL -> bin p1 (intersection l1 l2) (intersection r1 r2)
NOM -> Nil
intersection t1@(Bin _ _ _) (Tip kx2 bm2) = intersectBM t1
where intersectBM (Bin p1 l1 r1) | nomatch kx2 p1 = Nil
| left kx2 p1 = intersectBM l1
| otherwise = intersectBM r1
intersectBM (Tip kx1 bm1) | kx1 == kx2 = tip kx1 (bm1 .&. bm2)
| otherwise = Nil
intersectBM Nil = Nil
intersection (Bin _ _ _) Nil = Nil
intersection (Tip kx1 bm1) t2 = intersectBM t2
where intersectBM (Bin p2 l2 r2) | nomatch kx1 p2 = Nil
| left kx1 p2 = intersectBM l2
| otherwise = intersectBM r2
intersectBM (Tip kx2 bm2) | kx1 == kx2 = tip kx1 (bm1 .&. bm2)
| otherwise = Nil
intersectBM Nil = Nil
intersection Nil _ = Nil
-- | The intersection of a series of sets. Intersections are performed
-- left-to-right.
--
-- @since 0.8
intersections :: NonEmpty IntSet -> IntSet
intersections (s0 :| ss)
| null s0 = empty
| otherwise = List.foldr go id ss s0
where
go s r acc
| null acc' = empty
| otherwise = r acc'
where
acc' = intersection acc s
{-# INLINABLE intersections #-}
-- | @IntSet@s form a 'Semigroup' under 'intersection'.
--
-- A @Monoid@ instance is not defined because it would be impractical to
-- construct @mempty@, the @IntSet@ containing all @Int@s.
--
-- @since 0.8
newtype Intersection = Intersection { getIntersection :: IntSet }
deriving (Show, Eq, Ord)
instance Semigroup Intersection where
Intersection s1 <> Intersection s2 = Intersection (intersection s1 s2)
stimes = stimesIdempotent
{-# INLINABLE stimes #-}
sconcat =
#ifdef __GLASGOW_HASKELL__
coerce intersections
#else
Intersection . intersections . fmap getIntersection
#endif
{--------------------------------------------------------------------
Symmetric difference
--------------------------------------------------------------------}
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- The symmetric difference of two sets.
--
-- The result contains elements that appear in exactly one of the two sets.
--
-- @
-- symmetricDifference (fromList [0,2,4,6]) (fromList [0,3,6,9]) == fromList [2,3,4,9]
-- @
--
-- @since 0.8
symmetricDifference :: IntSet -> IntSet -> IntSet
symmetricDifference t1@(Bin p1 l1 r1) t2@(Bin p2 l2 r2) =
case treeTreeBranch p1 p2 of
ABL -> binCheckL p1 (symmetricDifference l1 t2) r1
ABR -> binCheckR p1 l1 (symmetricDifference r1 t2)
BAL -> binCheckL p2 (symmetricDifference t1 l2) r2
BAR -> binCheckR p2 l2 (symmetricDifference t1 r2)
EQL -> bin p1 (symmetricDifference l1 l2) (symmetricDifference r1 r2)
NOM -> link (unPrefix p1) t1 (unPrefix p2) t2
symmetricDifference t1@(Bin _ _ _) t2@(Tip kx2 bm2) = symDiffTip t2 kx2 bm2 t1
symmetricDifference t1@(Bin _ _ _) Nil = t1
symmetricDifference t1@(Tip kx1 bm1) t2 = symDiffTip t1 kx1 bm1 t2
symmetricDifference Nil t2 = t2
symDiffTip :: IntSet -> Int -> BitMap -> IntSet -> IntSet
symDiffTip !t1 !kx1 !bm1 = go
where
go t2@(Bin p2 l2 r2)
| nomatch kx1 p2 = linkKey kx1 t1 p2 t2
| left kx1 p2 = binCheckL p2 (go l2) r2
| otherwise = binCheckR p2 l2 (go r2)
go t2@(Tip kx2 bm2)
| kx1 == kx2 = tip kx1 (bm1 `xor` bm2)
| otherwise = link kx1 t1 kx2 t2
go Nil = t1
{--------------------------------------------------------------------
Subset
--------------------------------------------------------------------}
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- Is this a proper subset? (ie. a subset but not equal).
isProperSubsetOf :: IntSet -> IntSet -> Bool
isProperSubsetOf t1 t2
= case subsetCmp t1 t2 of
LT -> True
_ -> False
subsetCmp :: IntSet -> IntSet -> Ordering
subsetCmp t1@(Bin p1 l1 r1) (Bin p2 l2 r2) = case treeTreeBranch p1 p2 of
ABL -> GT
ABR -> GT
BAL -> case subsetCmp t1 l2 of GT -> GT ; _ -> LT
BAR -> case subsetCmp t1 r2 of GT -> GT ; _ -> LT
EQL -> subsetCmpEq
NOM -> GT -- disjoint
where
subsetCmpEq = case (subsetCmp l1 l2, subsetCmp r1 r2) of
(GT,_ ) -> GT
(_ ,GT) -> GT
(EQ,EQ) -> EQ
_ -> LT
subsetCmp (Bin _ _ _) _ = GT
subsetCmp (Tip kx1 bm1) (Tip kx2 bm2)
| kx1 /= kx2 = GT -- disjoint
| bm1 == bm2 = EQ
| bm1 .&. complement bm2 == 0 = LT
| otherwise = GT
subsetCmp t1@(Tip kx _) (Bin p l r)
| nomatch kx p = GT
| left kx p = case subsetCmp t1 l of GT -> GT ; _ -> LT
| otherwise = case subsetCmp t1 r of GT -> GT ; _ -> LT
subsetCmp (Tip _ _) Nil = GT -- disjoint
subsetCmp Nil Nil = EQ
subsetCmp Nil _ = LT
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- Is this a subset?
-- @(s1 \`isSubsetOf\` s2)@ tells whether @s1@ is a subset of @s2@.
isSubsetOf :: IntSet -> IntSet -> Bool
isSubsetOf t1@(Bin p1 l1 r1) (Bin p2 l2 r2) = case treeTreeBranch p1 p2 of
ABL -> False
ABR -> False
BAL -> isSubsetOf t1 l2
BAR -> isSubsetOf t1 r2
EQL -> isSubsetOf l1 l2 && isSubsetOf r1 r2
NOM -> False
isSubsetOf (Bin _ _ _) _ = False
isSubsetOf (Tip kx1 bm1) (Tip kx2 bm2) = kx1 == kx2 && bm1 .&. complement bm2 == 0
isSubsetOf t1@(Tip kx _) (Bin p l r)
| nomatch kx p = False
| left kx p = isSubsetOf t1 l
| otherwise = isSubsetOf t1 r
isSubsetOf (Tip _ _) Nil = False
isSubsetOf Nil _ = True
{--------------------------------------------------------------------
Disjoint
--------------------------------------------------------------------}
-- | \(O(\min(n, m \log \frac{2^W}{m})), m \leq n\).
-- Check whether two sets are disjoint (i.e. their intersection
-- is empty).
--
-- > disjoint (fromList [2,4,6]) (fromList [1,3]) == True
-- > disjoint (fromList [2,4,6,8]) (fromList [2,3,5,7]) == False
-- > disjoint (fromList [1,2]) (fromList [1,2,3,4]) == False
-- > disjoint (fromList []) (fromList []) == True
--
-- @since 0.5.11
disjoint :: IntSet -> IntSet -> Bool
disjoint t1@(Bin p1 l1 r1) t2@(Bin p2 l2 r2) = case treeTreeBranch p1 p2 of
ABL -> disjoint l1 t2
ABR -> disjoint r1 t2
BAL -> disjoint t1 l2
BAR -> disjoint t1 r2
EQL -> disjoint l1 l2 && disjoint r1 r2
NOM -> True
disjoint t1@(Bin _ _ _) (Tip kx2 bm2) = disjointBM t1
where disjointBM (Bin p1 l1 r1) | nomatch kx2 p1 = True
| left kx2 p1 = disjointBM l1
| otherwise = disjointBM r1
disjointBM (Tip kx1 bm1) | kx1 == kx2 = (bm1 .&. bm2) == 0
| otherwise = True
disjointBM Nil = True
disjoint (Bin _ _ _) Nil = True
disjoint (Tip kx1 bm1) t2 = disjointBM t2
where disjointBM (Bin p2 l2 r2) | nomatch kx1 p2 = True
| left kx1 p2 = disjointBM l2
| otherwise = disjointBM r2
disjointBM (Tip kx2 bm2) | kx1 == kx2 = (bm1 .&. bm2) == 0
| otherwise = True
disjointBM Nil = True
disjoint Nil _ = True
{--------------------------------------------------------------------
Filter
--------------------------------------------------------------------}
-- | \(O(n)\). Keep all elements that satisfy some predicate.
filter :: (Key -> Bool) -> IntSet -> IntSet
filter predicate t
= case t of
Bin p l r
-> bin p (filter predicate l) (filter predicate r)
Tip kx bm
-> tip kx (foldl'Bits 0 (bitPred kx) 0 bm)
Nil -> Nil
where bitPred kx bm bi | predicate (kx + bi) = bm .|. bitmapOfSuffix bi
| otherwise = bm
{-# INLINE bitPred #-}
-- | \(O(n \min(n,W))\). Map elements and collect the 'Just' results.
--
-- If the function is monotonically non-decreasing or monotonically
-- non-increasing, 'mapMaybe' takes \(O(n)\) time.
--
-- @since 0.8.1
mapMaybe :: (Key -> Maybe Key) -> IntSet -> IntSet
mapMaybe f t = finishB (foldl' go emptyB t)
where go b x = case f x of
Nothing -> b
Just x' -> insertB x' b
-- | \(O(n)\). partition the set according to some predicate.
partition :: (Key -> Bool) -> IntSet -> (IntSet,IntSet)
partition predicate0 t0 = toPair $ go predicate0 t0
where
go predicate t
= case t of
Bin p l r
-> let (l1 :*: l2) = go predicate l
(r1 :*: r2) = go predicate r
in bin p l1 r1 :*: bin p l2 r2
Tip kx bm
-> let bm1 = foldl'Bits 0 (bitPred kx) 0 bm
in tip kx bm1 :*: tip kx (bm `xor` bm1)
Nil -> (Nil :*: Nil)
where bitPred kx bm bi | predicate (kx + bi) = bm .|. bitmapOfSuffix bi
| otherwise = bm
{-# INLINE bitPred #-}
-- | \(O(\min(n,W))\). Take while a predicate on the elements holds.
-- The user is responsible for ensuring that for all @Int@s, @j \< k ==\> p j \>= p k@.
-- See note at 'spanAntitone'.
--
-- @
-- takeWhileAntitone p = 'fromDistinctAscList' . 'Data.List.takeWhile' p . 'toList'
-- takeWhileAntitone p = 'filter' p
-- @
--
-- @since 0.6.7
takeWhileAntitone :: (Key -> Bool) -> IntSet -> IntSet
takeWhileAntitone predicate t =
case t of
Bin p l r
| signBranch p ->
if predicate 0 -- handle negative numbers.
then binCheckL p (go predicate l) r
else go predicate r
_ -> go predicate t
where
go predicate' (Bin p l r)
| predicate' (unPrefix p) = binCheckR p l (go predicate' r)
| otherwise = go predicate' l
go predicate' (Tip kx bm) = tip kx (takeWhileAntitoneBits kx predicate' bm)
go _ Nil = Nil
-- | \(O(\min(n,W))\). Drop while a predicate on the elements holds.
-- The user is responsible for ensuring that for all @Int@s, @j \< k ==\> p j \>= p k@.
-- See note at 'spanAntitone'.
--
-- @
-- dropWhileAntitone p = 'fromDistinctAscList' . 'Data.List.dropWhile' p . 'toList'
-- dropWhileAntitone p = 'filter' (not . p)
-- @
--
-- @since 0.6.7
dropWhileAntitone :: (Key -> Bool) -> IntSet -> IntSet
dropWhileAntitone predicate t =
case t of
Bin p l r
| signBranch p ->
if predicate 0 -- handle negative numbers.
then go predicate l