Community
Modules 31

Data.IntSet

Finite Int Sets

The IntSet type represents a set of elements of type Int. An IntSet is strict in its elements.

For a walkthrough of the most commonly used functions see their sets introduction.

These modules are intended to be imported qualified, to avoid name clashes with Prelude functions, e.g.

 import Data.IntSet (IntSet)
 import qualified Data.IntSet as IntSet

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).

  • 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.

Performance information

The time complexity is given for each operation in [big-O notation](http:/en.wikipedia.orgwiki/Big_O_notation), with n referring to the number of entries in the map and W referring to the number of bits in an Int (32 or 64).

Operations like member, insert, and delete have a worst-case complexity of O(\min(n,W)). This means that the operation can become linear in the number of elements with a maximum of W -- the number of bits in an Int (32 or 64). These peculiar asymptotics are determined by the depth of the Patricia trees:

  • even for an extremely unbalanced tree, the depth cannot be larger than the number of elements n,

  • each level of a Patricia tree determines at least one more bit shared by all subelements, so there could not be more than W levels.

If all n elements in the tree are between 0 and N (or, say, between -N and N), the estimate can be refined to O(\min(n, \log N)). If the set is sufficiently "dense", this becomes O(\min(n, \log n)) or simply the familiar O(\log n), matching balanced binary trees.

The most performant scenario for IntSet are elements from a contiguous subset, in which case the complexity is proportional to \log n, capped by W. The worst scenario are exponentially growing elements 1,2,4, \ldots,2^n, for which complexity grows as fast as n but again is capped by W.

Binary set operations like union and intersection take O(\min(n, m \log \frac{2^W}{m})) time, where m and n are the sizes of the smaller and larger input sets respectively.

Set type

data IntSet

A set of integers.

type Key = Int

Construction

empty :: IntSet

O(1). The empty set.

singleton :: Key -> IntSet

O(1). A set of one element.

fromList :: [Key] -> IntSet

O(n \min(n,W)). Create a set from a list of integers.

If the keys are in sorted order, ascending or descending, this function takes O(n) time.

fromRange :: (Key, Key) -> IntSet

O(n / W). Create a set from a range of integers.

fromRange (low, high) == fromList [low..high]

fromAscList :: [Key] -> IntSet

O(n). Build a set from an ascending list of elements.

Warning: This function should be used only if the elements are in non-decreasing order. This precondition is not checked. Use fromList if the precondition may not hold.

fromDistinctAscList :: [Key] -> IntSet

O(n). Build a set from an ascending list of distinct elements.

fromDistinctAscList = fromAscList

See warning on fromAscList.

This definition exists for backwards compatibility. It offers no advantage over fromAscList.

fromDescList :: [Key] -> IntSet

O(n). Build a set from an descending list of elements.

Warning: This function should be used only if the elements are in non-increasing order. This precondition is not checked. Use fromList if the precondition may not hold.

Insertion

insert :: Key -> IntSet -> IntSet

O(\min(n,W)). Add a value to the set.

Deletion

delete :: Key -> IntSet -> IntSet

O(\min(n,W)). Delete a value in the set. Returns the original set when the value was not present.

pop :: Key -> IntSet -> Maybe IntSet

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])

Generalized insertion/deletion

alterF :: Functor f => (Bool -> f Bool) -> Key -> IntSet -> f IntSet

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)

Query

member :: Key -> IntSet -> Bool

O(\min(n,W)). Is the value a member of the set?

notMember :: Key -> IntSet -> Bool

O(\min(n,W)). Is the element not in the set?

lookupLT :: Key -> IntSet -> Maybe Key

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

lookupGT :: Key -> IntSet -> Maybe Key

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

lookupLE :: Key -> IntSet -> Maybe Key

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

lookupGE :: Key -> IntSet -> Maybe Key

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

null :: IntSet -> Bool

O(1). Is the set empty?

size :: IntSet -> Int

O(n). Cardinality of the set.

Note: Unlike Data.Set.size, this is not O(1).

See also: compareSize

compareSize :: IntSet -> Int -> Ordering

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.

isSubsetOf :: IntSet -> IntSet -> Bool

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.

isProperSubsetOf :: IntSet -> IntSet -> Bool

O(\min(n, m \log \frac{2^W}{m})), m \leq n. Is this a proper subset? (ie. a subset but not equal).

disjoint :: IntSet -> IntSet -> Bool

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

Combine

union :: IntSet -> IntSet -> IntSet

O(\min(n, m \log \frac{2^W}{m})), m \leq n. The union of two sets.

unions :: Foldable f => f IntSet -> IntSet

The union of a list of sets.

difference :: IntSet -> IntSet -> IntSet

O(\min(n, m \log \frac{2^W}{m})), m \leq n. Difference between two sets.

(\\) :: IntSet -> IntSet -> IntSet

O(\min(n, m \log \frac{2^W}{m})), m \leq n. See difference.

intersection :: IntSet -> IntSet -> IntSet

O(\min(n, m \log \frac{2^W}{m})), m \leq n. The intersection of two sets.

intersections :: NonEmpty IntSet -> IntSet

The intersection of a series of sets. Intersections are performed left-to-right.

symmetricDifference :: IntSet -> IntSet -> IntSet

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]

newtype Intersection

IntSets form a Semigroup under intersection.

A Monoid instance is not defined because it would be impractical to construct mempty, the IntSet containing all Ints.

Filter

filter :: (Key -> Bool) -> IntSet -> IntSet

O(n). Keep all elements that satisfy some predicate.

partition :: (Key -> Bool) -> IntSet -> (IntSet, IntSet)

O(n). partition the set according to some predicate.

takeWhileAntitone :: (Key -> Bool) -> IntSet -> IntSet

O(\min(n,W)). Take while a predicate on the elements holds. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. See note at spanAntitone.

takeWhileAntitone p = 'fromDistinctAscList' . 'Data.List.takeWhile' p . 'toList'
takeWhileAntitone p = 'filter' p

dropWhileAntitone :: (Key -> Bool) -> IntSet -> IntSet

O(\min(n,W)). Drop while a predicate on the elements holds. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k. See note at spanAntitone.

dropWhileAntitone p = 'fromDistinctAscList' . 'Data.List.dropWhile' p . 'toList'
dropWhileAntitone p = 'filter' (not . p)

spanAntitone :: (Key -> Bool) -> IntSet -> (IntSet, IntSet)

O(\min(n,W)). Divide a set at the point where a predicate on the elements stops holding. The user is responsible for ensuring that for all Ints, j < k ==> p j >= p k.

spanAntitone p xs = ('takeWhileAntitone' p xs, 'dropWhileAntitone' p xs)
spanAntitone p xs = 'partition' p xs

Note: if p is not actually antitone, then spanAntitone will split the set at some unspecified point.

mapMaybe :: (Key -> Maybe Key) -> IntSet -> IntSet

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.

split :: Key -> IntSet -> (IntSet, IntSet)

O(\min(n,W)). The expression (split x set) is a pair (set1,set2) where set1 comprises the elements of set less than x and set2 comprises the elements of set greater than x.

split 3 (fromList [1..5]) == (fromList [1,2], fromList [4,5])

splitMember :: Key -> IntSet -> (IntSet, Bool, IntSet)

O(\min(n,W)). Performs a split but also returns whether the pivot element was found in the original set.

splitRoot :: IntSet -> [IntSet]

O(1). Decompose a set into pieces based on the structure of the underlying tree. This function is useful for consuming a set in parallel.

No guarantee is made as to the sizes of the pieces; an internal, but deterministic process determines this. However, it is guaranteed that the pieces returned will be in ascending order (all elements in the first submap less than all elements in the second, and so on).

Examples:

splitRoot (fromList [1..120]) == [fromList [1..63],fromList [64..120]]
splitRoot empty == []

Note that the current implementation does not return more than two subsets, but you should not depend on this behaviour because it can change in the future without notice. Also, the current version does not continue splitting all the way to individual singleton sets -- it stops at some point.

Map

map :: (Key -> Key) -> IntSet -> IntSet

O(n \min(n,W)). map f s is the set obtained by applying f to each element of s.

If `f` is monotonically non-decreasing or monotonically non-increasing, this function takes O(n) time.

It's worth noting that the size of the result may be smaller if, for some (x,y), x /= y && f x == f y

mapMonotonic :: (Key -> Key) -> IntSet -> IntSet

O(n). The

mapMonotonic f s == map f s, but works only when f is strictly increasing. Semi-formally, we have:

and [x < y ==> f x < f y | x <- ls, y <- ls]
                    ==> mapMonotonic f s == map f s
    where ls = toList s

Warning: This function should be used only if f is monotonically strictly increasing. This precondition is not checked. Use map if the precondition may not hold.

Folds

foldr :: (Key -> b -> b) -> b -> IntSet -> b

O(n). Fold the elements in the set using the given right-associative binary operator, such that foldr f z == foldr f z . toAscList.

For example,

toAscList set = foldr (:) [] set

foldl :: (a -> Key -> a) -> a -> IntSet -> a

O(n). Fold the elements in the set using the given left-associative binary operator, such that foldl f z == foldl f z . toAscList.

For example,

toDescList set = foldl (flip (:)) [] set

foldMap :: Monoid a => (Key -> a) -> IntSet -> a

O(n). Map the elements in the set to a monoid and combine with (<>).

Strict folds

foldr' :: (Key -> b -> b) -> b -> IntSet -> b

O(n). A strict version of foldr. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.

foldl' :: (a -> Key -> a) -> a -> IntSet -> a

O(n). A strict version of foldl. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.

Legacy folds

fold :: (Key -> b -> b) -> b -> IntSet -> b

Use Data.IntSet.foldr instead

O(n). Fold the elements in the set using the given right-associative binary operator.

Min/Max

lookupMin :: IntSet -> Maybe Key

O(\min(n,W)). The minimal element of the set. Returns Nothing if the set is empty.

lookupMax :: IntSet -> Maybe Key

O(\min(n,W)). The maximal element of the set. Returns Nothing if the set is empty.

deleteMin :: IntSet -> IntSet

O(\min(n,W)). Delete the minimal element. Returns an empty set if the set is empty.

Note that this is a change of behaviour for consistency with Set &#8211; versions prior to 0.5 threw an error if the IntSet was already empty.

deleteMax :: IntSet -> IntSet

O(\min(n,W)). Delete the maximal element. Returns an empty set if the set is empty.

Note that this is a change of behaviour for consistency with Set &#8211; versions prior to 0.5 threw an error if the IntSet was already empty.

maxView :: IntSet -> Maybe (Key, IntSet)

O(\min(n,W)). Retrieves the maximal key of the set, and the set stripped of that element, or Nothing if passed an empty set.

minView :: IntSet -> Maybe (Key, IntSet)

O(\min(n,W)). Retrieves the minimal key of the set, and the set stripped of that element, or Nothing if passed an empty set.

findMin :: IntSet -> Key

O(\min(n,W)). The minimal element of the set. Calls error if the set is empty.

Note: This function is partial. Prefer lookupMin.

findMax :: IntSet -> Key

O(\min(n,W)). The maximal element of the set. Calls error if the set is empty.

Note: This function is partial. Prefer lookupMax.

deleteFindMin :: IntSet -> (Key, IntSet)

O(\min(n,W)). Delete and find the minimal element.

Calls error if the set is empty.

Note: This function is partial. Prefer minView.

deleteFindMax :: IntSet -> (Key, IntSet)

O(\min(n,W)). Delete and find the maximal element.

Calls error if the set is empty.

Note: This function is partial. Prefer maxView.

Conversion

List

elems :: IntSet -> [Key]

O(n). An alias of toAscList. The elements of a set in ascending order. Subject to list fusion.

toList :: IntSet -> [Key]

O(n). Convert the set to a list of elements. Subject to list fusion.

toAscList :: IntSet -> [Key]

O(n). Convert the set to an ascending list of elements. Subject to list fusion.

toDescList :: IntSet -> [Key]

O(n). Convert the set to a descending list of elements. Subject to list fusion.

Debugging

showTree :: IntSet -> String

O(n \min(n,W)). Show the tree that implements the set. The tree is shown in a compressed, hanging format.

showTreeWith :: Bool -> Bool -> IntSet -> String

O(n \min(n,W)). The expression (showTreeWith hang wide map) shows the tree that implements the set. If hang is True, a hanging tree is shown otherwise a rotated tree is shown. If wide is True, an extra wide version is shown.

Maintainer
libraries@haskell.org
Portability
portable
Copyright
(c) Daan Leijen 2002 (c) Joachim Breitner 2011
License
BSD-style
Build record and source files

Community contribution. The service has not verified this documentation. The generator reported 15 diagnostics.

Target: Linux on x86-64. Some inferred types and resolved links are not available.

Generator: aihc-haddock-aa6debbd-web-3

Metadata snapshot: 634f718c0d8cd970c4e2c511d2345d8fd36c6dc32b06343c2b4e914ffccbce7f

Open the dependency plan · Download the documentation model

Import a package

Enter a package name and an exact version from Hackage. The site contains imported versions only.