data IntMap a
A map of integers to values a.
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.
The type represents a finite map (sometimes called a dictionary)
from keys of type IntMap vInt to values of type v.
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 map implementation (see Data.Map).
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.
data IntMap aA map of integers to values a.
Bin :: Prefix -> (IntMap a) -> (IntMap a) -> IntMap aTip :: Key -> a -> IntMap aNil :: IntMap atype Key = Int(!) :: IntMap a -> Key -> aO(\min(n,W)). Find the value at a key.
Calls error when the element can not be found.
Note: This function is partial. Prefer !?.
fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map
fromList [(5,'a'), (3,'b')] ! 5 == 'a'(!?) :: IntMap a -> Key -> Maybe aO(\min(n,W)). Find the value at a key.
Returns Nothing when the element can not be found.
fromList [(5,'a'), (3,'b')] !? 1 == Nothing
fromList [(5,'a'), (3,'b')] !? 5 == Just 'a'(\\) :: IntMap a -> IntMap b -> IntMap aSame as difference.
null :: IntMap a -> BoolO(1). Is the map empty?
Data.IntMap.null (empty) == True
Data.IntMap.null (singleton 1 'a') == Falsesize :: IntMap a -> IntO(n). Number of entries in the map.
Note: Unlike Data.Map., this is not sizeO(1).
size empty == 0
size (singleton 1 'a') == 1
size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3See also: compareSize
compareSize :: IntMap a -> Int -> OrderingO(\min(n,c)). Compare the number of entries in the map to an Int.
compareSize m c returns the same result as compare ( but is
more efficient when size m) cc is smaller than the size of the map.
member :: Key -> IntMap a -> BoolO(\min(n,W)). Is the key a member of the map?
member 5 (fromList [(5,'a'), (3,'b')]) == True
member 1 (fromList [(5,'a'), (3,'b')]) == FalsenotMember :: Key -> IntMap a -> BoolO(\min(n,W)). Is the key not a member of the map?
notMember 5 (fromList [(5,'a'), (3,'b')]) == False
notMember 1 (fromList [(5,'a'), (3,'b')]) == Truelookup :: Key -> IntMap a -> Maybe aO(\min(n,W)). Look up the value at a key in the map. See also lookup.
findWithDefault :: a -> Key -> IntMap a -> aO(\min(n,W)). The expression (
returns the value at key findWithDefault def k map)k or returns def when the key is not an
element of the map.
findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'lookupLT :: Key -> IntMap a -> Maybe (Key, a)O(\min(n,W)). Find largest key smaller than the given one and return the
corresponding (key, value) pair.
lookupLT 3 (fromList [(3,'a'), (5,'b')]) == Nothing
lookupLT 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')lookupGT :: Key -> IntMap a -> Maybe (Key, a)O(\min(n,W)). Find smallest key greater than the given one and return the
corresponding (key, value) pair.
lookupGT 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
lookupGT 5 (fromList [(3,'a'), (5,'b')]) == NothinglookupLE :: Key -> IntMap a -> Maybe (Key, a)O(\min(n,W)). Find largest key smaller or equal to the given one and return
the corresponding (key, value) pair.
lookupLE 2 (fromList [(3,'a'), (5,'b')]) == Nothing
lookupLE 4 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
lookupLE 5 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')lookupGE :: Key -> IntMap a -> Maybe (Key, a)O(\min(n,W)). Find smallest key greater or equal to the given one and return
the corresponding (key, value) pair.
lookupGE 3 (fromList [(3,'a'), (5,'b')]) == Just (3, 'a')
lookupGE 4 (fromList [(3,'a'), (5,'b')]) == Just (5, 'b')
lookupGE 6 (fromList [(3,'a'), (5,'b')]) == Nothingdisjoint :: IntMap a -> IntMap b -> BoolO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Check whether the key sets of two maps are disjoint
(i.e. their intersection is empty).
disjoint (fromList [(2,'a')]) (fromList [(1,()), (3,())]) == True
disjoint (fromList [(2,'a')]) (fromList [(1,'a'), (2,'b')]) == False
disjoint (fromList []) (fromList []) == Truedisjoint a b == null (intersection a b)empty :: IntMap aO(1). The empty map.
empty == fromList []
size empty == 0singleton :: Key -> a -> IntMap aO(1). A map of one element.
singleton 1 'a' == fromList [(1, 'a')]
size (singleton 1 'a') == 1fromSet :: (Key -> a) -> IntSet -> IntMap aO(n). Build a map from an IntSet of keys and a function which for
each key computes its value.
fromSet (\k -> replicate k 'a') (Data.IntSet.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]fromSetA :: Applicative f => (Key -> f a) -> IntSet -> f (IntMap a)O(n). Build a map from an IntSet of keys and a function which for
each key computes its value, while within an Applicative context.
The Applicative actions are sequenced in order of increasing key.
let f k = if k == 0 then Nothing else Just (6 `div` k)
fromSetA f (Data.Set.fromList [1,2,3,4]) == Just (fromList [(1,6),(2,3),(3,2),(4,1)])
fromSetA f (Data.Set.fromList [0,1,2]) == NothingfromSetMaybe :: (Key -> Maybe a) -> IntSet -> IntMap aO(n). Build a map from an IntSet of keys and a function which for each
key optionally computes its value.
let f k = if even k then Just (replicate k 'a') else Nothing
fromSetMaybe f (Data.IntSet.fromList [1,2,3,4]) == fromList [(2,"aa"), (4,"aaaa")]fromSetMaybeA :: Applicative f => (Key -> f (Maybe a)) -> IntSet -> f (IntMap a)O(n). Build a map from an IntSet of keys and a function which for
each key optionally computes its value in an Applicative context.
The Applicative actions are sequenced in order of increasing key.
insert :: Key -> a -> IntMap a -> IntMap aO(\min(n,W)). Insert a new key/value pair in the map.
If the key is already present in the map, the associated value is
replaced with the supplied value, i.e. insert is equivalent to
.insertWith const
insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
insert 5 'x' empty == singleton 5 'x'insertWith :: (a -> a -> a) -> Key -> a -> IntMap a -> IntMap aO(\min(n,W)). Insert with a combining function.
will insert the pair (key, value) into insertWith f key value mpmp if key does
not exist in the map. If the key does exist, the function will
insert f new_value old_value.
insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
insertWith (++) 5 "xxx" empty == singleton 5 "xxx"Also see the performance note on fromListWith.
insertWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> IntMap aO(\min(n,W)). Insert with a combining function.
will insert the pair (key, value) into insertWithKey f key value mpmp if key does
not exist in the map. If the key does exist, the function will
insert f key new_value old_value.
let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
insertWithKey f 5 "xxx" empty == singleton 5 "xxx"Also see the performance note on fromListWith.
insertLookupWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> (Maybe a, IntMap a)O(\min(n,W)). The expression ()
is a pair where the first element is equal to (insertLookupWithKey f k x map)
and the second element equal to (lookup k map).insertWithKey f k x map
let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")This is how to define insertLookup using insertLookupWithKey:
let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])Also see the performance note on fromListWith.
delete :: Key -> IntMap a -> IntMap aO(\min(n,W)). Delete a key and its value from the map. When the key is not
a member of the map, the original map is returned.
delete 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
delete 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
delete 5 empty == emptypop :: Key -> IntMap a -> Maybe (a, IntMap a)O(\min(n,W)). Pop an entry from the map.
Returns Nothing if the key is not in the map. Otherwise returns Just the
value at the key and a map with the entry removed.
pop 1 (fromList [(0,"a"),(2,"b"),(4,"c")]) == Nothing
pop 2 (fromList [(0,"a"),(2,"b"),(4,"c")]) == Just ("b",fromList [(0,"a"),(4,"c")])
adjust :: (a -> a) -> Key -> IntMap a -> IntMap aO(\min(n,W)). Adjust a value at a specific key. When the key is not
a member of the map, the original map is returned.
adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
adjust ("new " ++) 7 empty == emptyadjustWithKey :: (Key -> a -> a) -> Key -> IntMap a -> IntMap aO(\min(n,W)). Adjust a value at a specific key. When the key is not
a member of the map, the original map is returned.
let f key x = (show key) ++ ":new " ++ x
adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
adjustWithKey f 7 empty == emptyupdate :: (a -> Maybe a) -> Key -> IntMap a -> IntMap aO(\min(n,W)). The expression () updates the value update f k mapx
at k (if it is in the map). If (f x) is Nothing, the element is
deleted. If it is (), the key Just yk is bound to the new value y.
let f x = if x == "a" then Just "new a" else Nothing
update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"updateWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> IntMap aO(\min(n,W)). The expression () updates the value update f k mapx
at k (if it is in the map). If (f k x) is Nothing, the element is
deleted. If it is (), the key Just yk is bound to the new value y.
let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"upsert :: (Maybe a -> a) -> Key -> IntMap a -> IntMap aO(\min(n,W)). Update the value at a key or insert a value if the key is
not in the map.
let inc = maybe 1 (+1)
upsert inc 100 (fromList [(100,1),(300,2)]) == fromList [(100,2),(300,2)]
upsert inc 200 (fromList [(100,1),(300,2)]) == fromList [(100,1),(200,1),(300,2)]
updateLookupWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> (Maybe a, IntMap a)O(\min(n,W)). Look up and update.
This function returns the original value, if it is updated.
This is different behavior than updateLookupWithKey.
Returns the original key value if the map entry is deleted.
let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:new a")])
updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")See also: pop
alter :: (Maybe a -> Maybe a) -> Key -> IntMap a -> IntMap aO(\min(n,W)). The expression () alters the value alter f k mapx at k, or absence thereof.
alter can be used to insert, delete, or update a value in an IntMap.
In short : .lookup k (alter f k m) = f (lookup k m)
alterF :: Functor f => (Maybe a -> f (Maybe a)) -> Key -> IntMap a -> f (IntMap a)O(\min(n,W)). The expression () alters the value alterF f k mapx at
k, or absence thereof. alterF can be used to inspect, insert, delete,
or update a value in an IntMap. In short : @lookup k <$> alterF f k m = f
(lookup k m)@.
alterF is the most general operation for working with an individual
key that may or may not be in a given map.
Note: alterF is a flipped version of the at combinator from
Control.Lens.At.
-- Lookup the value at the key, and also remove the existing value or set a new value.
lookupAndSet :: Key -> Maybe a -> IntMap a -> (Maybe a, IntMap a)
lookupAndSet k new = alterF (\\old -> (old, new)) k
-- Delete the value at the key. If it is absent the result is Nothing.
mustDelete :: Key -> IntMap a -> Maybe (IntMap a)
mustDelete = alterF (Nothing <$)
union :: IntMap a -> IntMap a -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The (left-biased) union of two maps.
It prefers the first map when duplicate keys are encountered,
i.e. ().union == unionWith const
union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]unionWith :: (a -> a -> a) -> IntMap a -> IntMap a -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The union with a combining function.
unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]Also see the performance note on fromListWith.
unionWithKey :: (Key -> a -> a -> a) -> IntMap a -> IntMap a -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The union with a combining function.
let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]Also see the performance note on fromListWith.
unions :: Foldable f => f (IntMap a) -> IntMap aThe union of a list of maps.
unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
== fromList [(3, "b"), (5, "a"), (7, "C")]
unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])]
== fromList [(3, "B3"), (5, "A3"), (7, "C")]unionsWith :: Foldable f => (a -> a -> a) -> f (IntMap a) -> IntMap aThe union of a list of maps, with a combining operation.
unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
== fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]difference :: IntMap a -> IntMap b -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Difference between two maps (based on keys).
difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"differenceWith :: (a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Difference with a combining function.
let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
== singleton 3 "b:B"differenceWithKey :: (Key -> a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Difference with a combining function. When two equal keys are
encountered, the combining function is applied to the key and both values.
If it returns Nothing, the element is discarded (proper set difference).
If it returns (), the element is updated with a new value Just yy.
let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
== singleton 3 "3:b|B"intersection :: IntMap a -> IntMap b -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The (left-biased) intersection of two maps (based on keys).
intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a"intersectionWith :: (a -> b -> c) -> IntMap a -> IntMap b -> IntMap cO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The intersection with a combining function.
intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"intersectionWithKey :: (Key -> a -> b -> c) -> IntMap a -> IntMap b -> IntMap cO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The intersection with a combining function.
let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"symmetricDifference :: IntMap a -> IntMap a -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The symmetric difference of two maps.
The result contains entries whose keys appear in exactly one of the two maps.
symmetricDifference
(fromList [(0,\'q\'),(2,\'b\'),(4,\'w\'),(6,\'o\')])
(fromList [(0,\'e\'),(3,\'r\'),(6,\'t\'),(9,\'s\')])
==
fromList [(2,\'b\'),(3,\'r\'),(4,\'w\'),(9,\'s\')]
compose :: IntMap c -> IntMap Int -> IntMap cGiven maps bc and ab, relate the keys of ab to the values of bc,
by using the values of ab as keys for lookups in bc.
Complexity: O(n * \min(m,W)) , where m is the size of the first argument
compose (fromList [('a', "A"), ('b', "B")]) (fromList [(1,'a'),(2,'b'),(3,'z')]) = fromList [(1,"A"),(2,"B")]('compose' bc ab '!?') = (bc '!?') <=< (ab '!?')
Note: Prior to v0.6.4, Data.IntMap.Strict exposed a version of
compose that forced the values of the output IntMap. This version does
not force these values.
type SimpleWhenMissing = WhenMissing IdentityA tactic for dealing with keys present in one map but not the
other in merge.
A tactic of type SimpleWhenMissing x z is an abstract
representation of a function of type Key -> x -> Maybe z.
type SimpleWhenMatched = WhenMatched IdentityA tactic for dealing with keys present in both maps in merge.
A tactic of type SimpleWhenMatched x y z is an abstract
representation of a function of type Key -> x -> y -> Maybe z.
runWhenMatched :: WhenMatched f x y z -> Key -> x -> y -> f (Maybe z)Along with zipWithMaybeAMatched, witnesses the isomorphism
between WhenMatched f x y z and Key -> x -> y -> f (Maybe z).
runWhenMissing :: WhenMissing f x y -> Key -> x -> f (Maybe y)Along with traverseMaybeMissing, witnesses the isomorphism
between WhenMissing f x y and Key -> x -> f (Maybe y).
merge :: SimpleWhenMissing a c -> SimpleWhenMissing b c -> SimpleWhenMatched a b c -> IntMap a -> IntMap b -> IntMap cMerge two maps.
merge takes two SimpleWhenMissing tactics, a SimpleWhenMatched tactic
and two maps. It uses the tactics to merge the maps. Its behavior
is best understood via its fundamental tactics, mapMaybeMissing
and zipWithMaybeMatched.
Consider
merge (mapMaybeMissing g1) (mapMaybeMissing g2) (zipWithMaybeMatched f) m1 m2
g1 k x = if k == 2 then Just ("1" ++ x) else Nothing
g2 k x = if k == 3 then Just ("2" ++ x) else Nothing
f k x y = if k == 6 then Just ("3" ++ x ++ y) else Nothing
m1 = fromList [(2,"a"), (4,"b"), (6,"c"), (8,"d"), (10,"e"), (12,"f")]
m2 = fromList [(3,"g"), (6,"h"), (9,"i"), (12,"j")]
merge will pass the keys and values to g1, g2, or f as appropriate,
producing a Maybe for each element.
m1: [ (2, "a"), (4, "b"), (6, "c"), (8, "d"), (10, "e"), (12, "f")]
m2: [ (3, "g"), (6, "h"), (9, "i"), (12, "j")]
result: [ g1 2 "a", g2 3 "g", g1 4 "b", f 6 "c" "h", g1 8 "d", g2 9 "i", g1 10 "e", f 12 "f" "j"]
= [Just "1a", Just "2g", Nothing, Just "3ch", Nothing, Nothing, Nothing, Nothing]
The result map contains the Just values.
>>> merge (mapMaybeMissing g1) (mapMaybeMissing g2) (zipWithMaybeMatched f) m1 m2
fromList [(2,"1a"), (3,"2g"), (6,"3ch")]The other tactics below are optimizations or simplifications of
mapMaybeMissing for special cases. Most importantly,
dropMissing drops all the keys.
preserveMissing leaves all the entries alone.
When merge is given three arguments, it is inlined at the call
site. To prevent excessive inlining, you should typically use
merge to define your custom combining functions.
Examples:
unionWithKey f = merge preserveMissing preserveMissing (zipWithMatched f)intersectionWithKey f = merge dropMissing dropMissing (zipWithMatched f)differenceWith f = merge diffPreserve diffDrop fsymmetricDifference = merge diffPreserve diffPreserve (\ _ _ _ -> Nothing)mapEachPiece f g h = merge (diffMapWithKey f) (diffMapWithKey g)What to do with keys in m1 but not m2
What to do with keys in m2 but not m1
What to do with keys in both m1 and m2
Map m1
Map m2
WhenMatched tacticsdropMatched :: Applicative f => WhenMatched f x y zWhen a key is found in both maps, drop the key and values.
zipWithMaybeMatched :: Applicative f => (Key -> x -> y -> Maybe z) -> WhenMatched f x y zWhen a key is found in both maps, apply a function to the key and values and maybe use the result in the merged map.
zipWithMaybeMatched
:: (Key -> x -> y -> Maybe z)
-> SimpleWhenMatched x y zzipWithMatched :: Applicative f => (Key -> x -> y -> z) -> WhenMatched f x y zWhen a key is found in both maps, apply a function to the key and values and use the result in the merged map.
zipWithMatched
:: (Key -> x -> y -> z)
-> SimpleWhenMatched x y zWhenMissing tacticsmapMaybeMissing :: Applicative f => (Key -> x -> Maybe y) -> WhenMissing f x yMap over the entries whose keys are missing from the other
map, optionally removing some. This is the most powerful
SimpleWhenMissing tactic, but others are usually more efficient.
mapMaybeMissing :: (Key -> x -> Maybe y) -> SimpleWhenMissing x ymapMaybeMissing f = traverseMaybeMissing (\k x -> pure (f k x))but mapMaybeMissing uses fewer unnecessary Applicative
operations.
dropMissing :: Applicative f => WhenMissing f x yDrop all the entries whose keys are missing from the other map.
dropMissing :: SimpleWhenMissing x ydropMissing = mapMaybeMissing (\_ _ -> Nothing)but dropMissing is much faster.
preserveMissing :: Applicative f => WhenMissing f x xPreserve, unchanged, the entries whose keys are missing from the other map.
preserveMissing :: SimpleWhenMissing x xpreserveMissing = Merge.Lazy.mapMaybeMissing (\_ x -> Just x)but preserveMissing is much faster.
mapMissing :: Applicative f => (Key -> x -> y) -> WhenMissing f x yMap over the entries whose keys are missing from the other map.
mapMissing :: (k -> x -> y) -> SimpleWhenMissing x ymapMissing f = mapMaybeMissing (\k x -> Just $ f k x)but mapMissing is somewhat faster.
filterMissing :: Applicative f => (Key -> x -> Bool) -> WhenMissing f x xFilter the entries whose keys are missing from the other map.
filterMissing :: (k -> x -> Bool) -> SimpleWhenMissing x xfilterMissing f = Merge.Lazy.mapMaybeMissing $ \k x -> guard (f k x) *> Just xbut this should be a little faster.
data WhenMissing f x yA tactic for dealing with keys present in one map but not the
other in merge or mergeA.
A tactic of type WhenMissing f k x z is an abstract representation
of a function of type Key -> x -> f (Maybe z).
WhenMissing :: IntMap x -> f (IntMap y) -> Key -> x -> f (Maybe y) -> WhenMissing f x ymissingSubtree :: WhenMissing f x y -> IntMap x -> f (IntMap y)missingKey :: WhenMissing f x y -> Key -> x -> f (Maybe y)newtype WhenMatched f x y zA tactic for dealing with keys present in both maps in merge
or mergeA.
A tactic of type WhenMatched f x y z is an abstract representation
of a function of type Key -> x -> y -> f (Maybe z).
WhenMatched :: Key -> x -> y -> f (Maybe z) -> WhenMatched f x y zmatchedKey :: WhenMatched f x y z -> Key -> x -> y -> f (Maybe z)mergeA :: (Applicative f) => WhenMissing f a c -> WhenMissing f b c -> WhenMatched f a b c -> IntMap a -> IntMap b -> f (IntMap c)An applicative version of merge.
mergeA takes two WhenMissing tactics, a WhenMatched
tactic and two maps. It uses the tactics to merge the maps.
Its behavior is best understood via its fundamental tactics,
traverseMaybeMissing and zipWithMaybeAMatched.
Behaves just like merge while allowing Applicative effects. Effects are
performed in increasing order of keys.
Consider
mergeA (traverseMaybeMissing g1)
(traverseMaybeMissing g2)
(zipWithMaybeAMatched f)
m1
m2
g1 k x = let z = if k == 2 then Just ("1" ++ x) else Nothing
in z <$ putStrLn ("g1 " ++ show (k, x))
g2 k x = let z = if k == 3 then Just ("2" ++ x) else Nothing
in z <$ putStrLn ("g2 " ++ show (k, x))
f k x y = let z = if k == 6 then Just ("3" ++ x ++ y) else Nothing
in z <$ putStrLn ("f " ++ show (k, x, y))
m1 = fromList [(2,"a"), (4,"b"), (6,"c"), (8,"d"), (10,"e"), (12,"f")]
m2 = fromList [(3,"g"), (6,"h"), (9,"i"), (12,"j")]
As with merge, the result map is [(2,"1a"), (3,"2g"), (6,"3ch")].
Additionally, g1, g2, and f perform IO effects, printing in
increasing order of key.
>>> mergeA (traverseMaybeMissing g1) (traverseMaybeMissing g2) (zipWithMaybeAMatched f) m1 m2
g1 (2,"a")
g2 (3,"g")
g1 (4,"b")
f (6,"c","h")
g1 (8,"d")
g2 (9,"i")
g1 (10,"e")
f (12,"f","j")
fromList [(2,"1a"),(3,"2g"),(6,"3ch")]The other tactics below are optimizations or simplifications of
traverseMaybeMissing for special cases. Most importantly,
dropMissing drops all the keys.
preserveMissing leaves all the entries alone.
mapMaybeMissing does not use the Applicative context.
When mergeA is given three arguments, it is inlined at the call
site. To prevent excessive inlining, you should generally only use
mergeA to define custom combining functions.
data Pair a = Pair !a !a deriving Functor
instance Applicative Pair where
pure x = Pair x x
liftA2 f (Pair x1 y1) (Pair x2 y2) = Pair (f x1 x2) (f y1 y2)
-- | Calculate the left-biased union and intersection of two maps.
unionIntersection :: IntMap a -> IntMap a -> (IntMap a, IntMap a)
unionIntersection m1 m2 =
case mergeA preserveAndDropMissing preserveAndDropMissing preserveLeftMatched m1 m2 of
Pair mu mi -> (mu, mi)
where
-- use Pair to build the union and intersection together
preserveAndDropMissing = 'whenMissing' (\\_k x -> Pair (Just x) Nothing) (\\m -> Pair m empty)
preserveLeftMatched = 'zipWithMaybeAMatched' (\\_k x1 _x2 -> Pair (Just x1) (Just x1))
import Data.Functor.Const (Const(..))
import Data.Monoid (All(..))
-- | Whether the keys of the first map are a subset of the keys of the second map.
keysAreSubsetOf :: IntMap a -> IntMap b -> Bool
keysAreSubsetOf m1 m2 =
getAll (getConst (mergeA isEmpty 'dropMissing' 'dropMatched' m1 m2))
where
isEmpty = 'whenMissing' (\\_k _x -> Const (All False)) (\\m -> Const (All (null m)))
What to do with keys in m1 but not m2
What to do with keys in m2 but not m1
What to do with keys in both m1 and m2
Map m1
Map m2
WhenMatched tacticsmerge work for
mergeA as well. Furthermore, the following
are available.zipWithMaybeAMatched :: (Key -> x -> y -> f (Maybe z)) -> WhenMatched f x y zWhen a key is found in both maps, apply a function to the key and values, perform the resulting action, and maybe use the result in the merged map.
This is the fundamental WhenMatched tactic.
zipWithAMatched :: Applicative f => (Key -> x -> y -> f z) -> WhenMatched f x y zWhen a key is found in both maps, apply a function to the key and values to produce an action and use its result in the merged map.
WhenMissing tacticsmerge work for
mergeA as well. Furthermore, the following
are available.traverseMaybeMissing :: Applicative f => (Key -> x -> f (Maybe y)) -> WhenMissing f x yTraverse over the entries whose keys are missing from the other
map, optionally producing values to put in the result. This is
the most powerful WhenMissing tactic, but others are usually
more efficient.
traverseMissing :: Applicative f => (Key -> x -> f y) -> WhenMissing f x yTraverse over the entries whose keys are missing from the other map.
filterAMissing :: Applicative f => (Key -> x -> f Bool) -> WhenMissing f x xFilter the entries whose keys are missing from the other map
using some Applicative action.
filterAMissing f = Merge.Lazy.traverseMaybeMissing $
\k x -> (\b -> guard b *> Just x) <$> f k xbut this should be a little faster.
whenMissing :: (Key -> x -> f (Maybe y)) -> (IntMap x -> f (IntMap y)) -> WhenMissing f x yCreate a WhenMissing from two functions.
whenMissing must be called with two functions f and g such that
g = . traverseMaybeWithKey fg may be a more efficient way of applying
f to all key-value pairs in an IntMap.
Warning: It is the caller's responsibility to ensure the above property.
preserveMissing :: Applicative f => WhenMissing f x x
preserveMissing = whenMissing f g
where
f _k x = pure (Just x)
g m = pure m
-- Note that this satisfies g = traverseMaybeWithKey f
import Data.Functor.Const (Const(..))
import Data.Monoid (All(..))
-- For a usage of this, see examples on mergeA
isEmpty :: WhenMissing (Const All) x y
isEmpty = whenMissing f g
where
f _k _x = Const (All False)
g m = Const (All (null m))
-- Note that this satisfies g = traverseMaybeWithKey f
mergeWithKey :: (Key -> a -> b -> Maybe c) -> (IntMap a -> IntMap c) -> (IntMap b -> IntMap c) -> IntMap a -> IntMap b -> IntMap cO(\min(n, m \log \frac{2^W}{m})), m \leq n.
A high-performance universal combining function. Using
mergeWithKey, all combining functions can be defined without any loss of
efficiency (with exception of union, difference and intersection,
where sharing of some nodes is lost with mergeWithKey).
Warning: Please make sure you know what is going on when using mergeWithKey,
otherwise you can be surprised by unexpected code growth or even
corruption of the data structure.
When mergeWithKey is given three arguments, it is inlined to the call
site. You should therefore use mergeWithKey only to define your custom
combining functions. For example, you could define unionWithKey,
differenceWithKey and intersectionWithKey as
myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2When calling , a function combining two
mergeWithKey combine only1 only2IntMaps is created, such that
if a key is present in both maps, it is passed with both corresponding
values to the combine function. Depending on the result, the key is either
present in the result with specified value, or is left out;
a nonempty subtree present only in the first map is passed to only1 and
the output is added to the result;
a nonempty subtree present only in the second map is passed to only2 and
the output is added to the result.
The only1 and only2 methods must return a map with a subset (possibly empty) of the keys of the given map.
The values can be modified arbitrarily. Most common variants of only1 and
only2 are id and , but for example const empty or
map f could be used for any filterWithKey ff.
mergeWithKey' :: (Prefix -> IntMap c -> IntMap c -> IntMap c) -> (IntMap a -> IntMap b -> IntMap c) -> (IntMap a -> IntMap c) -> (IntMap b -> IntMap c) -> IntMap a -> IntMap b -> IntMap cmap :: (a -> b) -> IntMap a -> IntMap bO(n). Map a function over all values in the map.
map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]mapWithKey :: (Key -> a -> b) -> IntMap a -> IntMap bO(n). Map a function over all values in the map.
let f key x = (show key) ++ ":" ++ x
mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]traverseWithKey :: Applicative t => (Key -> a -> t b) -> IntMap a -> t (IntMap b)O(n).
That is, behaves exactly like a regular traverseWithKey f s == fromList <$> traverse ((k, v) -> (,) k <$> f k v) (toList m)traverse except that the traversing
function also has access to the key associated with a value.
traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')])
traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == NothingtraverseMaybeWithKey :: Applicative f => (Key -> a -> f (Maybe b)) -> IntMap a -> f (IntMap b)O(n). Traverse keys/values and collect the Just results.
mapAccum :: (a -> b -> (a, c)) -> a -> IntMap b -> (a, IntMap c)O(n). The function threads an accumulating
argument through the map in ascending order of keys.mapAccum
let f a b = (a ++ b, b ++ "X")
mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])mapAccumWithKey :: (a -> Key -> b -> (a, c)) -> a -> IntMap b -> (a, IntMap c)O(n). The function threads an accumulating
argument through the map in ascending order of keys.mapAccumWithKey
let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])mapAccumRWithKey :: (a -> Key -> b -> (a, c)) -> a -> IntMap b -> (a, IntMap c)O(n). The function threads an accumulating
argument through the map in descending order of keys.mapAccumRWithKey
mapKeys :: (Key -> Key) -> IntMap a -> IntMap aO(n \min(n,W)).
is the map obtained by applying mapKeys f sf to each key of s.
If `f` is monotonically non-decreasing or monotonically non-increasing, this
function takes O(n) time.
The size of the result may be smaller if f maps two or more distinct
keys to the same new key. In this case the value at the greatest of the
original keys is retained.
mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")]
mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"mapKeysWith :: (a -> a -> a) -> (Key -> Key) -> IntMap a -> IntMap aO(n \min(n,W)).
is the map obtained by applying mapKeysWith c f sf to each key of s.
If `f` is monotonically non-decreasing or monotonically non-increasing, this
function takes O(n) time.
The size of the result may be smaller if f maps two or more distinct
keys to the same new key. In this case the associated values will be
combined using c.
mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"Also see the performance note on fromListWith.
mapKeysMonotonic :: (Key -> Key) -> IntMap a -> IntMap aO(n).
, but works only when mapKeysMonotonic f s == mapKeys f sf
is strictly monotonic.
That is, for any values x and y, if x < y then f x < f y.
Semi-formally, we have:
and [x < y ==> f x < f y | x <- ls, y <- ls]
==> mapKeysMonotonic f s == mapKeys f s
where ls = keys sThis means that f maps distinct original keys to distinct resulting keys.
This function has slightly better performance than mapKeys.
Warning: This function should be used only if f is monotonically
strictly increasing. This precondition is not checked. Use mapKeys if the
precondition may not hold.
mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]foldr :: (a -> b -> b) -> b -> IntMap a -> bO(n). Fold the values in the map using the given right-associative
binary operator, such that .foldr f z == foldr f z . elems
For example,
elems map = foldr (:) [] maplet f a len = len + (length a)
foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4foldl :: (a -> b -> a) -> a -> IntMap b -> aO(n). Fold the values in the map using the given left-associative
binary operator, such that .foldl f z == foldl f z . elems
For example,
elems = reverse . foldl (flip (:)) []let f len a = len + (length a)
foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4foldrWithKey :: (Key -> a -> b -> b) -> b -> IntMap a -> bO(n). Fold the keys and values in the map using the given right-associative
binary operator, such that
.foldrWithKey f z == foldr (uncurry f) z . toAscList
For example,
keys map = foldrWithKey (\k x ks -> k:ks) [] maplet f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"foldlWithKey :: (a -> Key -> b -> a) -> a -> IntMap b -> aO(n). Fold the keys and values in the map using the given left-associative
binary operator, such that
.foldlWithKey f z == foldl (\z' (kx, x) -> f z' kx x) z . toAscList
For example,
keys = reverse . foldlWithKey (\ks k x -> k:ks) []let f result k a = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
foldlWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (3:b)(5:a)"foldMapWithKey :: Monoid m => (Key -> a -> m) -> IntMap a -> mO(n). Fold the keys and values in the map using the given monoid, such that
foldMapWithKey f = fold . mapWithKey f
This can be an asymptotically faster than foldrWithKey or foldlWithKey for some monoids.
foldr' :: (a -> b -> b) -> b -> IntMap a -> bO(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 -> b -> a) -> a -> IntMap b -> aO(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.
foldrWithKey' :: (Key -> a -> b -> b) -> b -> IntMap a -> bO(n). A strict version of foldrWithKey. Each application of the operator is
evaluated before using the result in the next application. This
function is strict in the starting value.
foldlWithKey' :: (a -> Key -> b -> a) -> a -> IntMap b -> aO(n). A strict version of foldlWithKey. Each application of the operator is
evaluated before using the result in the next application. This
function is strict in the starting value.
elems :: IntMap a -> [a]O(n).
Return all elements of the map in the ascending order of their keys.
Subject to list fusion.
elems (fromList [(5,"a"), (3,"b")]) == ["b","a"]
elems empty == []keys :: IntMap a -> [Key]O(n). Return all keys of the map in ascending order. Subject to list
fusion.
keys (fromList [(5,"a"), (3,"b")]) == [3,5]
keys empty == []assocs :: IntMap a -> [(Key, a)]O(n). An alias for toAscList. Returns all key/value pairs in the
map in ascending key order. Subject to list fusion.
assocs (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
assocs empty == []keysSet :: IntMap a -> IntSetO(n). The set of all keys of the map.
keysSet (fromList [(5,"a"), (3,"b")]) == Data.IntSet.fromList [3,5]
keysSet empty == Data.IntSet.emptytoList :: IntMap a -> [(Key, a)]O(n). Convert the map to a list of key/value pairs. Subject to list
fusion.
toList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]
toList empty == []fromList :: [(Key, a)] -> IntMap aO(n \min(n,W)). Create a map from a list of key/value pairs.
If the list contains more than one value for the same key, the last value
for the key is retained.
If the keys are in sorted order, ascending or descending, this function
takes O(n) time.
fromList [] == empty
fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]fromListWith :: (a -> a -> a) -> [(Key, a)] -> IntMap aO(n \min(n,W)). Build a map from a list of key/value pairs with a combining function.
If the keys are in sorted order, ascending or descending, this function
takes O(n) time.
fromListWith (++) [(5,"a"), (5,"b"), (3,"x"), (5,"c")] == fromList [(3, "x"), (5, "cba")]
fromListWith (++) [] == emptyNote the reverse ordering of "cba" in the example.
The symmetric combining function f is applied in a left-fold over the list, as f new old.
See also: fromListUpsert
You should ensure that the given f is fast with this order of arguments.
Symmetric functions may be slow in one order, and fast in another. For the common case of collecting values of matching keys in a list, as above:
The complexity of (++) a b is O(a), so it is fast when given a short list as its first argument.
Thus:
fromListWith (++) (replicate 1000000 (3, "x")) -- O(n), fast
fromListWith (flip (++)) (replicate 1000000 (3, "x")) -- O(n²), extremely slowbecause they evaluate as, respectively:
fromList [(3, "x" ++ ("x" ++ "xxxxx..xxxxx"))] -- O(n)
fromList [(3, ("xxxxx..xxxxx" ++ "x") ++ "x")] -- O(n²)Thus, to get good performance with an operation like (++) while also preserving
the same order as in the input list, reverse the input:
fromListWith (++) (reverse [(5,"a"), (5,"b"), (5,"c")]) == fromList [(5, "abc")]and it is always fast to combine singleton-list values [v] with fromListWith (++), as in:
fromListWith (++) $ reverse $ map (\(k, v) -> (k, [v])) someListOfTuplesfromListWithKey :: (Key -> a -> a -> a) -> [(Key, a)] -> IntMap aO(n \min(n,W)). Build a map from a list of key/value pairs with a combining function.
If the keys are in sorted order, ascending or descending, this function
takes O(n) time.
let f key new_value old_value = show key ++ ":" ++ new_value ++ "|" ++ old_value
fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"c")] == fromList [(3, "3:a|b"), (5, "5:c|5:b|a")]
fromListWithKey f [] == emptyAlso see the performance note on fromListWith.
See also: fromListUpsert
fromListUpsert :: (a -> Maybe b -> b) -> [(Key, a)] -> IntMap bO(n \min(n,W). Build a map from a list of key/value pairs with a
combining function.
If the keys are in sorted order, ascending or descending, this function
takes O(n) time.
The result is equivalent to performing an upsert for every key/value in
the list.
fromListUpsert f = foldl' (\\m (k, x) -> 'upsert' (f x) k m) 'empty'
let f x = maybe [x] (x:)
fromListUpsert f [(5,'a'), (5,'b'), (3,'c'), (3,'d'), (5,'e')] == fromList [(3,"dc"), (5,"eba")]toAscList :: IntMap a -> [(Key, a)]O(n). Convert the map to a list of key/value pairs where the
keys are in ascending order. Subject to list fusion.
toAscList (fromList [(5,"a"), (3,"b")]) == [(3,"b"), (5,"a")]toDescList :: IntMap a -> [(Key, a)]O(n). Convert the map to a list of key/value pairs where the keys
are in descending order. Subject to list fusion.
toDescList (fromList [(5,"a"), (3,"b")]) == [(5,"a"), (3,"b")]fromAscList :: [(Key, a)] -> IntMap aO(n). Build a map from a list of key/value pairs where
the keys are in ascending order.
Warning: This function should be used only if the keys are in
non-decreasing order. This precondition is not checked. Use fromList if the
precondition may not hold.
fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]fromAscListWith :: (a -> a -> a) -> [(Key, a)] -> IntMap aO(n). Build a map from a list of key/value pairs where
the keys are in ascending order, with a combining function on equal keys.
Warning: This function should be used only if the keys are in
non-decreasing order. This precondition is not checked. Use fromListWith if
the precondition may not hold.
fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]Also see the performance note on fromListWith.
See also: fromAscListUpsert
fromAscListWithKey :: (Key -> a -> a -> a) -> [(Key, a)] -> IntMap aO(n). Build a map from a list of key/value pairs where
the keys are in ascending order, with a combining function on equal keys.
Warning: This function should be used only if the keys are in
non-decreasing order. This precondition is not checked. Use fromListWithKey
if the precondition may not hold.
let f key new_value old_value = show key ++ ":" ++ new_value ++ "|" ++ old_value
fromAscListWithKey f [(3,"b"), (3,"a"), (5,"a"), (5,"b"), (5,"c")] == fromList [(3, "3:a|b"), (5, "5:c|5:b|a")]
fromAscListWithKey f [] == emptyAlso see the performance note on fromListWith.
See also: fromAscListUpsert
fromAscListUpsert :: (a -> Maybe b -> b) -> [(Key, a)] -> IntMap bO(n). Build a map from an ascending list in linear time with a
combining function for equal keys.
Warning: This function should be used only if the keys are in
non-decreasing order. This precondition is not checked. Use fromListUpsert
if the precondition may not hold.
let f x = maybe [x] (x:)
fromAscListUpsert f [(3,'a'), (3,'b'), (5,'c'), (5,'d'), (5,'e')] == fromList [(3,"ba"), (5,"edc")]fromDistinctAscList :: [(Key, a)] -> IntMap aO(n). Build a map from a list of key/value pairs where
the keys are in ascending order and all distinct.
fromDistinctAscList = fromAscList
See warning on fromAscList.
This definition exists for backwards compatibility. It offers no advantage
over fromAscList.
fromDescList :: [(Key, a)] -> IntMap aO(n). Build a map from a list of key/value pairs where
the keys are in descending order.
Warning: This function should be used only if the keys are in
non-increasing order. This precondition is not checked. Use fromList if the
precondition may not hold.
fromDescList [(5,"a"), (3,"b")] == fromList [(3,"b"), (5,"a")]
fromDescList [(5,"a"), (5,"b"), (3,"b")] == fromList [(3,"b"), (5,"b")]fromDescListUpsert :: (a -> Maybe b -> b) -> [(Key, a)] -> IntMap bO(n). Build a map from a descending list in linear time with a
combining function for equal keys.
Warning: This function should be used only if the keys are in
non-increasing order. This precondition is not checked. Use fromListUpsert
if the precondition may not hold.
let f x = maybe [x] (x:)
fromDescListUpsert f [(5,'a'), (5,'b'), (5,'c'), (3,'d'), (3,'e')] == fromList [(3,"ed"), (5,"cba")]filter :: (a -> Bool) -> IntMap a -> IntMap aO(n). Keep all values that satisfy some predicate.
filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
filter (> "x") (fromList [(5,"a"), (3,"b")]) == empty
filter (< "a") (fromList [(5,"a"), (3,"b")]) == emptyfilterKeys :: (Key -> Bool) -> IntMap a -> IntMap aO(n). Keep all keys that satisfy some predicate.
filterKeys p = 'filterWithKey' (\\k _ -> p k)
filterKeys (> 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"filterWithKey :: (Key -> a -> Bool) -> IntMap a -> IntMap aO(n). Keep all keys/values that satisfy some predicate.
filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"restrictKeys :: IntMap a -> IntSet -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The restriction of a map to the keys in a set.
m \`restrictKeys\` s = 'filterWithKey' (\\k _ -> k ``IntSet.member`` s) m
withoutKeys :: IntMap a -> IntSet -> IntMap aO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Remove all the keys in a given set from a map.
m \`withoutKeys\` s = 'filterWithKey' (\\k _ -> k ``IntSet.notMember`` s) m
partition :: (a -> Bool) -> IntMap a -> (IntMap a, IntMap a)O(n). Partition the map according to some predicate. The first
map contains all elements that satisfy the predicate, the second all
elements that fail the predicate. See also split.
partition (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
partition (> "x") (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])partitionWithKey :: (Key -> a -> Bool) -> IntMap a -> (IntMap a, IntMap a)O(n). Partition the map according to some predicate. The first
map contains all elements that satisfy the predicate, the second all
elements that fail the predicate. See also split.
partitionWithKey (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b")
partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], empty)
partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3, "b"), (5, "a")])takeWhileAntitone :: (Key -> Bool) -> IntMap a -> IntMap aO(\min(n,W)). Take while a predicate on the keys 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 . fst) . 'toList'
takeWhileAntitone p = 'filterWithKey' (\\k _ -> p k)
dropWhileAntitone :: (Key -> Bool) -> IntMap a -> IntMap aO(\min(n,W)). Drop while a predicate on the keys 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 . fst) . 'toList'
dropWhileAntitone p = 'filterWithKey' (\\k _ -> not (p k))
spanAntitone :: (Key -> Bool) -> IntMap a -> (IntMap a, IntMap a)O(\min(n,W)). Divide a map at the point where a predicate on the keys 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 = 'partitionWithKey' (\\k _ -> p k) xs
Note: if p is not actually antitone, then spanAntitone will split the map
at some unspecified point.
mapMaybe :: (a -> Maybe b) -> IntMap a -> IntMap bO(n). Map values and collect the Just results.
let f x = if x == "a" then Just "new a" else Nothing
mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"mapMaybeWithKey :: (Key -> a -> Maybe b) -> IntMap a -> IntMap bO(n). Map keys/values and collect the Just results.
let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"mapEither :: (a -> Either b c) -> IntMap a -> (IntMap b, IntMap c)O(n). Map values and separate the Left and Right results.
let f a = if a < "c" then Left a else Right a
mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
== (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
== (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])mapEitherWithKey :: (Key -> a -> Either b c) -> IntMap a -> (IntMap b, IntMap c)O(n). Map keys/values and separate the Left and Right results.
let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
== (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
== (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])split :: Key -> IntMap a -> (IntMap a, IntMap a)O(\min(n,W)). The expression () is a pair split k map(map1,map2)
where all keys in map1 are lower than k and all keys in
map2 larger than k. Any key equal to k is found in neither map1 nor map2.
split 2 (fromList [(5,"a"), (3,"b")]) == (empty, fromList [(3,"b"), (5,"a")])
split 3 (fromList [(5,"a"), (3,"b")]) == (empty, singleton 5 "a")
split 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
split 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", empty)
split 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], empty)splitLookup :: Key -> IntMap a -> (IntMap a, Maybe a, IntMap a)O(\min(n,W)). Performs a split but also returns whether the pivot
key was found in the original map.
splitLookup 2 (fromList [(5,"a"), (3,"b")]) == (empty, Nothing, fromList [(3,"b"), (5,"a")])
splitLookup 3 (fromList [(5,"a"), (3,"b")]) == (empty, Just "b", singleton 5 "a")
splitLookup 4 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Nothing, singleton 5 "a")
splitLookup 5 (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", Just "a", empty)
splitLookup 6 (fromList [(5,"a"), (3,"b")]) == (fromList [(3,"b"), (5,"a")], Nothing, empty)splitRoot :: IntMap a -> [IntMap a]O(1). Decompose a map into pieces based on the structure
of the underlying tree. This function is useful for consuming a
map 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 (zip [1..6::Int] ['a'..])) ==
[fromList [(1,'a'),(2,'b'),(3,'c')],fromList [(4,'d'),(5,'e'),(6,'f')]]splitRoot empty == []Note that the current implementation does not return more than two submaps, but you should not depend on this behaviour because it can change in the future without notice.
isSubmapOf :: Eq a => IntMap a -> IntMap a -> BoolO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Is this a submap?
Defined as ().isSubmapOf = isSubmapOfBy (==)
isSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> BoolO(\min(n, m \log \frac{2^W}{m})), m \leq n.
The expression () returns isSubmapOfBy f m1 m2True if
all keys in m1 are in m2, and when f returns True when
applied to their respective values. For example, the following
expressions are all True:
isSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
isSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])But the following are all False:
isSubmapOfBy (==) (fromList [(1,2)]) (fromList [(1,1),(2,2)])
isSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])isProperSubmapOf :: Eq a => IntMap a -> IntMap a -> BoolO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Is this a proper submap? (ie. a submap but not equal).
Defined as ().isProperSubmapOf = isProperSubmapOfBy (==)
isProperSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> BoolO(\min(n, m \log \frac{2^W}{m})), m \leq n.
Is this a proper submap? (ie. a submap but not equal).
The expression () returns isProperSubmapOfBy f m1 m2True when
keys m1 and keys m2 are not equal,
all keys in m1 are in m2, and when f returns True when
applied to their respective values. For example, the following
expressions are all True:
isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])But the following are all False:
isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])lookupMin :: IntMap a -> Maybe (Key, a)O(\min(n,W)). The minimal key of the map. Returns Nothing if the map is empty.
lookupMax :: IntMap a -> Maybe (Key, a)O(\min(n,W)). The maximal key of the map. Returns Nothing if the map is empty.
findMin :: IntMap a -> (Key, a)O(\min(n,W)). The minimal key of the map. Calls error if the map is empty.
Note: This function is partial. Prefer lookupMin.
findMax :: IntMap a -> (Key, a)O(\min(n,W)). The maximal key of the map. Calls error if the map is empty.
Note: This function is partial. Prefer lookupMax.
deleteMin :: IntMap a -> IntMap aO(\min(n,W)). Delete the minimal key. Returns an empty map if the map is empty.
Note that this is a change of behaviour for consistency with Map –
versions prior to 0.5 threw an error if the IntMap was already empty.
deleteMax :: IntMap a -> IntMap aO(\min(n,W)). Delete the maximal key. Returns an empty map if the map is empty.
Note that this is a change of behaviour for consistency with Map –
versions prior to 0.5 threw an error if the IntMap was already empty.
deleteFindMin :: IntMap a -> ((Key, a), IntMap a)O(\min(n,W)). Delete and find the minimal element.
Calls error if the map is empty.
Note: This function is partial. Prefer minViewWithKey.
deleteFindMax :: IntMap a -> ((Key, a), IntMap a)O(\min(n,W)). Delete and find the maximal element.
Calls error if the map is empty.
Note: This function is partial. Prefer maxViewWithKey.
updateMin :: (a -> Maybe a) -> IntMap a -> IntMap aO(\min(n,W)). Update the value at the minimal key.
updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"updateMax :: (a -> Maybe a) -> IntMap a -> IntMap aO(\min(n,W)). Update the value at the maximal key.
updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"updateMinWithKey :: (Key -> a -> Maybe a) -> IntMap a -> IntMap aO(\min(n,W)). Update the value at the minimal key.
updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"updateMaxWithKey :: (Key -> a -> Maybe a) -> IntMap a -> IntMap aO(\min(n,W)). Update the value at the maximal key.
updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"minView :: IntMap a -> Maybe (a, IntMap a)O(\min(n,W)). Retrieves the minimal key of the map, and the map
stripped of that element, or Nothing if passed an empty map.
maxView :: IntMap a -> Maybe (a, IntMap a)O(\min(n,W)). Retrieves the maximal key of the map, and the map
stripped of that element, or Nothing if passed an empty map.
minViewWithKey :: IntMap a -> Maybe ((Key, a), IntMap a)O(\min(n,W)). Retrieves the minimal (key,value) pair of the map, and
the map stripped of that element, or Nothing if passed an empty map.
minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a")
minViewWithKey empty == NothingmaxViewWithKey :: IntMap a -> Maybe ((Key, a), IntMap a)O(\min(n,W)). Retrieves the maximal (key,value) pair of the map, and
the map stripped of that element, or Nothing if passed an empty map.
maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b")
maxViewWithKey empty == NothingshowTree :: Show a => IntMap a -> StringO(n \min(n,W)). Show the tree that implements the map. The tree is shown
in a compressed, hanging format.
showTreeWith :: Show a => Bool -> Bool -> IntMap a -> StringO(n \min(n,W)). The expression () shows
the tree that implements the map. If showTreeWith hang wide maphang is
True, a hanging tree is shown otherwise a rotated tree is shown. If
wide is True, an extra wide version is shown.
link :: Int -> IntMap a -> Int -> IntMap a -> IntMap aLink two IntMaps. The maps must not be empty. The Prefixes of the two
maps must be different. k1 must share the prefix of t1 and k2 must
share the prefix of t2.
linkKey :: Key -> IntMap a -> Prefix -> IntMap a -> IntMap aLink two IntMaps. The maps must not be empty. The Prefixes of the two
maps must be different. k1 must share the prefix of t1. p2 must be the
prefix of t2.
bin :: Prefix -> IntMap a -> IntMap a -> IntMap abinCheckL :: Prefix -> IntMap a -> IntMap a -> IntMap abinCheckR :: Prefix -> IntMap a -> IntMap a -> IntMap adata MonoState aMSNada :: MonoState aMSPush :: Key -> a -> (Stack a) -> MonoState adata Stack aNada :: Stack aPush :: Int -> (IntMap a) -> (Stack a) -> Stack aascLinkTop :: Stack a -> Int -> IntMap a -> Int -> Stack aascLinkAll :: MonoState a -> IntMap adescInsert :: Int -> a -> MonoState a -> MonoState adescLinkTop :: Int -> IntMap a -> Int -> Stack a -> Stack adescLinkAll :: MonoState a -> IntMap adata IntMapBuilder aBNil :: IntMapBuilder aBTip :: Int -> a -> (BStack a) -> IntMapBuilder adata BStack aBNada :: BStack aBLeft :: Prefix -> (IntMap a) -> (BStack a) -> BStack aBRight :: Prefix -> (IntMap a) -> (BStack a) -> BStack aemptyB :: IntMapBuilder ainsertB :: Key -> a -> IntMapBuilder a -> IntMapBuilder afinishB :: IntMapBuilder a -> IntMap amoveToB :: Key -> Key -> a -> BStack a -> MoveResult adata MoveResult aMoveResult :: (Maybe a) -> (BStack a) -> MoveResult atreeFromIntSetTip :: (Int -> a) -> (Prefix -> a -> a -> a) -> Int -> Word -> aIntMap.Merge.Lazy and IntMap.Merge.StrictmapWhenMissing :: Monad f => (a -> b) -> WhenMissing f x a -> WhenMissing f x bMap covariantly over a .WhenMissing f x
mapWhenMatched :: Functor f => (a -> b) -> WhenMatched f x y a -> WhenMatched f x y bMap covariantly over a .WhenMatched f x y
lmapWhenMissing :: (b -> a) -> WhenMissing f a x -> WhenMissing f b xMap contravariantly over a .WhenMissing f _ x
contramapFirstWhenMatched :: (b -> a) -> WhenMatched f a y z -> WhenMatched f b y zMap contravariantly over a .WhenMatched f _ y z
contramapSecondWhenMatched :: (b -> a) -> WhenMatched f x a z -> WhenMatched f x b zMap contravariantly over a .WhenMatched f x _ z
mapGentlyWhenMissing :: Functor f => (a -> b) -> WhenMissing f x a -> WhenMissing f x bMap covariantly over a , using only a
'Functor f' constraint.WhenMissing f x
mapGentlyWhenMatched :: Functor f => (a -> b) -> WhenMatched f x y a -> WhenMatched f x y bMap covariantly over a , using only a
'Functor f' constraint.WhenMatched f k x
instance Lift a => Lift (IntMap a)instance Monoid (IntMap a)mempty = empty
instance Semigroup (IntMap a)(<>) = union
instance Foldable.Foldable IntMapFolds in order of increasing key.
instance Traversable IntMapTraverses in order of increasing key.
instance NFData a => NFData (IntMap a)instance NFData1 IntMapinstance Data a => Data (IntMap a)instance Monad f => Functor (WhenMissing f x)instance Monad f => Category.Category (WhenMissing f)instance Monad f => Applicative (WhenMissing f x)Equivalent to ReaderT k (ReaderT x (MaybeT f)).
instance Monad f => Monad (WhenMissing f x)Equivalent to ReaderT k (ReaderT x (MaybeT f)).
instance Functor f => Functor (WhenMatched f x y)instance Monad f => Category.Category (WhenMatched f x)instance Monad f => Applicative (WhenMatched f x y)Equivalent to ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))
instance Monad f => Monad (WhenMatched f x y)Equivalent to ReaderT Key (ReaderT x (ReaderT y (MaybeT f)))
instance GHCExts.IsList (IntMap a)instance Eq a => Eq (IntMap a)instance Eq1 IntMapinstance Ord a => Ord (IntMap a)instance Ord1 IntMapinstance Functor IntMapinstance Show a => Show (IntMap a)instance Show1 IntMapinstance (Read e) => Read (IntMap e)instance Read1 IntMapCommunity 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