h,t.      !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~                                                                                                                                                        %:(c) Clark Gaebel 2012 (c) Johan Tibel 2012 BSD-stylelibraries@haskell.orgportableSafe<0Return a word where only the highest bit is set.(c) David Feuer 2016 BSD-stylelibraries@haskell.orgportable Safe-Inferred Create an empty bit queue builder. This is represented as a single guard bit in the most significant position. Enqueue a bit. This works by shifting the queue right one bit, then setting the most significant bit as requested. Convert a bit queue builder to a bit queue. This shifts in a new guard bit on the left, and shifts right until the old guard bit falls off. 3Dequeue an element, or discover the queue is empty.Convert a bit queue to a list of bits by unconsing. This is used to test that the queue functions properly.    NoneCoerce the second argument of a function. Conceptually, can be thought of as:  (f .^# g) x y = f x (g y) :However it is most useful when coercing the arguments to : ) foldl f b . fmap g = foldl (f .^# g) b  ! Safe-Inferred'  "None Checks if two pointers are equal. Yes means yes; no means maybe. The values should be forced to at least WHNF before comparison to get moderately reliable results. Checks if two pointers are equal, without requiring them to have the same type. The values should be forced to at least WHNF before comparison to get moderately reliable results.  # #$ Safe-Inferred% Safe-Inferred  Safe'The same as a regular Haskell pair, but  (x :*: _|_) = (_|_ :*: y) = _|_ )Convert a strict pair to a standard pair.&(c) Daan Leijen 2002 BSD-stylelibraries@haskell.orgportable Trustworthy 7T Sets form a   under <. The needle is present in the original set. We return the set where the needle is deleted. The needle is not present in the original set. We return the set with the needle inserted.A set of values a."=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. See ;.#O(1). Is this the empty set?$O(1)$. The number of elements in the set.% O(\log n). Is the element in the set?& O(\log n) . Is the element not in the set?' O(\log n)2. Find largest element smaller than the given one. lookupLT 3 (fromList [3, 5]) == Nothing lookupLT 5 (fromList [3, 5]) == Just 3( O(\log n)3. Find smallest element greater than the given one. lookupGT 4 (fromList [3, 5]) == Just 5 lookupGT 5 (fromList [3, 5]) == Nothing) O(\log n)9. 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* O(\log n):. 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+O(1). The empty set.,O(1). Create a singleton set.- O(\log n). Insert an element in a set. If the set already contains an element equal to the given value, it is replaced with the new value.. O(\log n). Delete an element from a set./ containers O(\log n) (/ f x s) can delete or insert x in s4 depending on whether an equal element is found in s. In short: % x <$> / f x s = f (% x s) Note that unlike -, / will not. replace an element equal to the given value.Note: / is a variant of the at combinator from Control.Lens.At.0=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. (s1 `isProperSubsetOf` s2) indicates whether s1 is a proper subset of s2. s1 `isProperSubsetOf` s2 = s1 1 s2 && s1 /= s2 1=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. (s1 `isSubsetOf` s2) indicates whether s1 is a subset of s2. s1 `isSubsetOf` s2 = all (%& s2) s1 s1 `isSubsetOf` s2 = null (s1 ; s2) s1 `isSubsetOf` s2 = s1 :" s2 == s2 s1 `isSubsetOf` s2 = s1 < s2 == s1 2 containers =O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < 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 xs 2 ys = null (xs < ys) 3 containers  O(\log n). The minimal element of a set.4 O(\log n). The minimal element of a set.5 containers  O(\log n). The maximal element of a set.6 O(\log n). The maximal element of a set.7 O(\log n). Delete the minimal element. Returns an empty set if the set is empty.8 O(\log n). Delete the maximal element. Returns an empty set if the set is empty.91The union of the sets in a Foldable structure : (9 == E : +).:=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. The union of two sets, preferring the first set when equal elements are encountered.;=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. Difference of two sets.Return elements of the first set not existing in the second set. =difference (fromList [5, 3]) (fromList [5, 7]) == singleton 3<=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. The intersection of two sets. Elements of the result come from the first set, so for example import qualified Data.Set as S data AB = A | B deriving Show instance Ord AB where compare _ _ = EQ instance Eq AB where _ == _ = True main = print (S.singleton A `S.intersection` S.singleton B, S.singleton B `S.intersection` S.singleton A)prints (fromList [A],fromList [B]).=The intersection of a series of sets. Intersections are performed left-to-right.>O(n)1. Filter all elements that satisfy the predicate.?O(n). Partition the set into two sets, one with all elements that satisfy the predicate and one with all elements that don't satisfy the predicate. See also P.@ O(n \log n). @ f s! is the set obtained by applying f to each element of s.It's worth noting that the size of the result may be smaller if, for some (x,y), x /= y && f x == f yAO(n). TheA f s == @ f s, but works only when f is strictly increasing.  The precondition is not checked. Semi-formally, we have: and [x < y ==> f x < f y | x <- ls, y <- ls] ==> mapMonotonic f s == map f s where ls = toList sBO(n). Fold the elements in the set using the given right-associative binary operator. This function is an equivalent of C( and is present for compatibility only.Please note that fold will be deprecated in the future and removed.CO(n). Fold the elements in the set using the given right-associative binary operator, such that C f z == '( f z . I. For example,  toAscList set = foldr (:) [] setDO(n). A strict version of C. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.EO(n). Fold the elements in the set using the given left-associative binary operator, such that E f z == ') f z . I. For example, (toDescList set = foldl (flip (:)) [] setFO(n). A strict version of E. Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.GO(n). An alias of I. The elements of a set in ascending order. Subject to list fusion.HO(n). Convert the set to a list of elements. Subject to list fusion.IO(n). Convert the set to an ascending list of elements. Subject to list fusion.JO(n). Convert the set to a descending list of elements. Subject to list fusion.K O(n \log n)'. Create a set from a list of elements.If the elements are ordered, a linear-time implementation is used.LO(n)6. Build a set from an ascending list in linear time. :The precondition (input list is ascending) is not checked.M containersO(n)6. Build a set from a descending list in linear time. ;The precondition (input list is descending) is not checked.NO(n). Build a set from an ascending list of distinct elements in linear time. The precondition (input list is strictly ascending) is not checked.O containersO(n). Build a set from a descending list of distinct elements in linear time. The precondition (input list is strictly descending) is not checked.P O(\log n). The expression (P 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.Q O(\log n) . Performs a P but also returns whether the pivot element was found in the original set.R containers O(\log n) . Return the index of an element, which is its zero-based index in the sorted sequence of elements. The index is a number from 0 up to, but not including, the $ of the set. Calls  when the element is not a % of the set. findIndex 2 (fromList [5,3]) Error: element is not in the set findIndex 3 (fromList [5,3]) == 0 findIndex 5 (fromList [5,3]) == 1 findIndex 6 (fromList [5,3]) Error: element is not in the setS containers O(\log n) . Lookup the index of an element, which is its zero-based index in the sorted sequence of elements. The index is a number from 0 up to, but not including, the $ of the set. isJust (lookupIndex 2 (fromList [5,3])) == False fromJust (lookupIndex 3 (fromList [5,3])) == 0 fromJust (lookupIndex 5 (fromList [5,3])) == 1 isJust (lookupIndex 6 (fromList [5,3])) == FalseT containers O(\log n). Retrieve an element by its index, i.e. by its zero-based index in the sorted sequence of elements. If the index7 is out of range (less than zero, greater or equal to $ of the set),  is called. elemAt 0 (fromList [5,3]) == 3 elemAt 1 (fromList [5,3]) == 5 elemAt 2 (fromList [5,3]) Error: index out of rangeU containers O(\log n). Delete the element at index, i.e. by its zero-based index in the sorted sequence of elements. If the index7 is out of range (less than zero, greater or equal to $ of the set),  is called. deleteAt 0 (fromList [5,3]) == singleton 5 deleteAt 1 (fromList [5,3]) == singleton 3 deleteAt 2 (fromList [5,3]) Error: index out of range deleteAt (-1) (fromList [5,3]) Error: index out of rangeV containers O(\log n). Take a given number of elements in order, beginning with the smallest ones.  take n = N . '* n . I W containers O(\log n). Drop a given number of elements in order, beginning with the smallest ones.  drop n = N . '+ n . I X O(\log n)$. Split a set at a particular index. splitAt !n !xs = (V n xs, W n xs) Y containers O(\log n). Take while a predicate on the elements holds. The user is responsible for ensuring that for all elements j and k in the set, j < k ==> p j >= p k. See note at [. takeWhileAntitone p = N . ,- p . H takeWhileAntitone p = > p Z containers O(\log n). Drop while a predicate on the elements holds. The user is responsible for ensuring that for all elements j and k in the set, j < k ==> p j >= p k. See note at [. dropWhileAntitone p = N . ,. p . H dropWhileAntitone p = > (not . p) [ containers O(\log n). Divide a set at the point where a predicate on the elements stops holding. The user is responsible for ensuring that for all elements j and k in the set, j < k ==> p j >= p k. spanAntitone p xs = (Y p xs, Z* 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 where the predicate switches from holding to not holding (where the predicate is seen to hold before the first element and to fail after the last element).^ O(\log n)&. Delete and find the minimal element. 0deleteFindMin set = (findMin set, deleteMin set)_ O(\log n)&. Delete and find the maximal element. 0deleteFindMax set = (findMax set, deleteMax set)` O(\log n). Retrieves the minimal key of the set, and the set stripped of that element, or   if passed an empty set.a O(\log n). Retrieves the maximal key of the set, and the set stripped of that element, or   if passed an empty set.c containersO(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 subset less than all elements in the second, and so on). Examples: splitRoot (fromList [1..6]) == [fromList [1,2,3],fromList [4],fromList [5,6]] splitRoot empty == []Note that the current implementation does not return more than three subsets, but you should not depend on this behaviour because it can change in the future without notice.d containers  O(2^n \log n)?. Calculate the power set of a set: the set of all its subsets. t % powerSet s == t 1 s Example: powerSet (fromList [1,2,3]) = fromList $ map fromList [[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]] e containers O(nm).. Calculate the Cartesian product of two sets. cartesianProduct xs ys = fromList $ liftA2 (,) (toList xs) (toList ys) Example: cartesianProduct (fromList [1,2]) (fromList ['a','b']) = fromList [(1,'a'), (1,'b'), (2,'a'), (2,'b')] f containers O(n+m)+. Calculate the disjoint union of two sets. # disjointUnion xs ys = map Left xs : map Right ysExample: disjointUnion (fromList [1,2]) (fromList ["hi", "bye"]) = fromList [Left 1, Left 2, Right "hi", Right "bye"] g O(n \log n). Show the tree that implements the set. The tree is shown in a compressed, hanging format.h O(n \log n). The expression (showTreeWith hang wide map.) shows the tree that implements the set. If hang is True, a hanging6 tree is shown otherwise a rotated tree is shown. If wide is  !, an extra wide version is shown. Set> putStrLn $ showTreeWith True False $ fromDistinctAscList [1..5] 4 +--2 | +--1 | +--3 +--5 Set> putStrLn $ showTreeWith True True $ fromDistinctAscList [1..5] 4 | +--2 | | | +--1 | | | +--3 | +--5 Set> putStrLn $ showTreeWith False True $ fromDistinctAscList [1..5] +--5 | 4 | | +--3 | | +--2 | +--1iO(n).. Test if the internal set structure is valid.m containers n containers o containers s containersu!Folds in order of increasing key.v containers~ containers"/jbe.U_^87;2fWZTG+>R64BEFCDLMNOK-<=01\*(S)'53@Aa%]`&#?dgh,$[PXQcVYIJH:9i ! !"#$%&'()*102+,-./d:9;<=ef>YZ[?PQcSRTUVWX@ACEDFB354678^_a`GHKIJLNMOghibj\]" (c) Daan Leijen 2002 BSD-stylelibraries@haskell.orgportableSafeU"/e.U_^87;2fWZTG+>R64BEFCDLMNOK-<01*(S)'53@Aa%`&#?dgh,$[PXQcVYIJH:9i+,KLMNOd-./%&'()*#$102:9;"YZ[?PQcSRTUVWX@ACEDFB354678^_a`GHIJghi(c) Ross Paterson 2005 (c) Louis Wasserman 2009 (c) Bertram Felgenhauer, David Feuer, Ross Paterson, and Milan Straka 2014 BSD-stylelibraries@haskell.orgportable Trustworthy(78=$View of the right end of a sequence.empty sequencethe sequence minus the rightmost element, and the rightmost element#View of the left end of a sequence.empty sequence-leftmost element and the rest of the sequence Sometimes, we want to emphasize that we are viewing a node as a top-level digit of a   tree. 0A finger tree whose digits are all ones and twos A finger tree whose top level has only Two and/or Three digits, and whose other levels have only One and Two digits. A Rigid tree is precisely what one gets by unzipping/inverting a 2-3 tree, so it is precisely what we need to turn a finger tree into in order to transform it into a 2-3 tree.!General-purpose finite sequences. containersA bidirectional pattern synonym viewing the rear of a non-empty sequence. containersA bidirectional pattern synonym viewing the front of a non-empty sequence. containers;A bidirectional pattern synonym matching an empty sequence. We use this to help the types work out for splices in the Lift instance. Things get a bit yucky otherwise.  ) does most of the hard work of computing liftA2 f xs ys. It produces the center part of a finger tree, with a prefix corresponding to the first element of xs and a suffix corresponding to its last element omitted; the missing suffix and prefix are added by the caller. For the recursive call, it squashes the prefix and the suffix into the center tree. Once it gets to the bottom, it turns the tree into a 2-3 tree, applies  > to produce the main body, and glues all the pieces together.f itself is a bit horrifying because of the nested types involved. Its job is to map over the *elements* of a 2-3 tree, rather than the subtrees. If we used a higher-order nested type with MPTC, we could probably use a class, but as it is we have to build up f# explicitly through the recursion.Description of parametersTypesa2 remains constant through recursive calls (in the DeepTh case), while b and c do not:  liftAMiddle calls itself at types Node b and Node c.Values  is used when the original xs :: Sequence a has at least two elements, so it can be decomposed by taking off the first and last elements: xs = firstx <: midxs :> lastxthe first two arguments ffirstx, flastx :: b -> c are equal to f firstx and f lastx, where f :: a -> b -> c5 is the third argument. This ensures sharing when f computes some data upon being partially applied to its first argument. The way f gets accumulated also ensures sharing for the middle section.'the fourth argument is the middle part midxs, always constant.#the last argument, a tuple of type Rigid b, holds all the elements of ys, in three parts: a middle part around which the recursion is structured, surrounded by a prefix and a suffix that accumulate elements on the side as we walk down the middle. Invariants 1. Viewing the various trees as the lists they represent (the types of the toList functions are given a few paragraphs below): toListFTN result = (ffirstx <$> (toListThinN m ++ toListD sf)) ++ (f <$> toListFTE midxs <*> (toListD pr ++ toListThinN m ++ toListD sf)) ++ (flastx <$> (toListD pr ++ toListThinN m)) 2. s = size m + size pr + size sf 3. size (ffirstx y) = size (flastx y) = size (f x y) = size y for any (x :: a) (y :: b)Projecting invariant 1 on sizes, using 2 and 3 to simplify, we have the following corollary. It is weaker than invariant 1, but it may be easier to keep track of. /1a. size result = s * (size midxs + 1) + size mIn invariant 1, the types of the auxiliary functions are as follows for reference: toListFTE :: FingerTree (Elem a) -> [a] toListFTN :: FingerTree (Node c) -> [c] toListThinN :: Thin (Node b) -> [b] toListD :: Digit12 b -> [b] O(mn) (incremental) Takes an O(m)% function and a finger tree of size n> and maps the function over the tree leaves. Unlike the usual  2, the function is applied to the "leaves" of the  (i.e., given a FingerTree (Elem a)., it applies the function to elements of type Elem a), replacing the leaves with subtrees of at least the same height, e.g., Node(Node(Elem y)). The multiplier argument serves to make the annotations match up properly.  O(\log n)4 (incremental) Takes the extra flexibility out of a 6 to make it a genuine 2-3 finger tree. The result of   will have only two and three digits at the top level and only one and two digits elsewhere. If the tree has fewer than four elements,  6 will simply extract them, and will not build a tree.  O(\log n) (incremental) Takes a tree whose left side has been rigidified and finishes the job.  O(\log n) (incremental) Rejigger a finger tree so the digits are all ones and twos. containers O(n) <. Intersperse an element between the elements of a sequence. intersperse a empty = empty intersperse a (singleton x) = singleton x intersperse a (fromList [x,y]) = fromList [x,a,y] intersperse a (fromList [x,y,z]) = fromList [x,a,y,a,z] Given the size of a digit and the digit itself, efficiently converts it to a FingerTree.   takes an Applicative-wrapped construction of a piece of a FingerTree, assumed to always have the same size (which is put in the second argument), and replicates it as many times as specified. This is a generalization of , which itself is a generalization of many Data.Sequence methods. ?Replicate each element of a sequence the given number of times.%replicateEach 3 [1,2] = [1,1,1,2,2,2] 'replicateEach n xs = xs >>= replicate n O(1) . The empty sequence. O(1) . A singleton sequence. O(\log n) .  replicate n x is a sequence consisting of n copies of x. is an   version of  , and makes  O(\log n)  calls to   and  . *replicateA n x = sequenceA (replicate n x) is the Seq counterpart of Control.Monad./0. )replicateM n x = sequence (replicate n x)For  base >= 4.8.0 and containers >= 0.5.11,  is a synonym for . O(\log k).  k xs forms a sequence of length k by repeatedly concatenating xs with itself. xs may only be empty if k is 0.2cycleTaking k = fromList . take k . cycle . toList O(1) . Add an element to the left end of a sequence. Mnemonic: a triangle with the single element at the pointy end. O(1) . Add an element to the right end of a sequence. Mnemonic: a triangle with the single element at the pointy end. O(\log(\min(n_1,n_2))) . Concatenate two sequences.Builds a sequence from a seed value. Takes time linear in the number of generated elements. WARNING: If the number of generated elements is infinite, this method will not terminate. f x is equivalent to  ( (  swap . f) x). O(n) . Constructs a sequence by repeated application of a function to a seed value. iterateN n f x = fromList (Prelude.take n (Prelude.iterate f x)) O(1) . Is this the empty sequence? O(1) ). The number of elements in the sequence. O(1) %. Analyse the left end of a sequence. O(1) &. Analyse the right end of a sequence. is similar to :, but returns a sequence of reduced values from the left: scanl f z (fromList [x1, x2, ...]) = fromList [z, z `f` x1, (z `f` x1) `f` x2, ...] is a variant of % that has no starting value argument: scanl1 f (fromList [x1, x2, ...]) = fromList [x1, x1 `f` x2, ...] is the right-to-left dual of . is a variant of % that has no starting value argument. O(\log(\min(i,n-i))) . The element at the specified position, counting from 0. The argument should thus be a non-negative integer less than the size of the sequence. If the position is out of range,  fails with an error.xs `index` i = toList xs !! i Caution:  necessarily delays retrieving the requested element until the result is forced. It can therefore lead to a space leak if the result is stored, unforced, in another structure. To retrieve an element immediately without forcing it, use  or . containers O(\log(\min(i,n-i))) . The element at the specified position, counting from 0. If the specified position is negative or at least the length of the sequence,  returns  .;0 <= i < length xs ==> lookup i xs == Just (toList xs !! i)1i < 0 || i >= length xs ==> lookup i xs = NothingUnlike , this can be used to retrieve an element without forcing it. For example, to insert the fifth element of a sequence xs into a 1 m at key k, you could use /case lookup 5 xs of Nothing -> m Just x -> 2 k x m  containers O(\log(\min(i,n-i))) . A flipped, infix version of . O(\log(\min(i,n-i))) . Replace the element at the specified position. If the position is out of range, the original sequence is returned. containers O(\log(\min(i,n-i))) . Update the element at the specified position. If the position is out of range, the original sequence is returned.  can lead to poor performance and even memory leaks, because it does not force the new value before installing it in the sequence.  should usually be preferred. containers O(\log(\min(i,n-i))) . Update the element at the specified position. If the position is out of range, the original sequence is returned. The new value is forced before it is installed in the sequence. adjust' f i xs = case xs !? i of Nothing -> xs Just x -> let !x' = f x in update i x' xs  containers O(\log(\min(i,n-i))) .  i x xs inserts x into xs at the index i), shifting the rest of the sequence over. insertAt 2 x (fromList [a,b,c,d]) = fromList [a,b,x,c,d] insertAt 4 x (fromList [a,b,c,d]) = insertAt 10 x (fromList [a,b,c,d]) = fromList [a,b,c,d,x] 7insertAt i x xs = take i xs >< singleton x >< drop i xs containers O(\log(\min(i,n-i))) . Delete the element of a sequence at a given index. Return the original sequence if the index is out of range. deleteAt 2 [a,b,c,d] = [a,b,d] deleteAt 4 [a,b,c,d] = deleteAt (-1) [a,b,c,d] = [a,b,c,d] A generalization of  ,  takes a mapping function that also depends on the element's index, and applies it to every element in the sequence. containers is a version of  7 that also offers access to the index of each element. containers O(n) . Convert a given sequence length and a function representing that sequence into a sequence. containers O(n) 5. Create a sequence consisting of the elements of an  . Note that the resulting sequence elements may be evaluated lazily (as on GHC), so you must force the entire structure to be sure that the original array can be garbage-collected. O(\log(\min(i,n-i)))  . The first i elements of a sequence. If i is negative,  i s yields the empty sequence. If the sequence contains fewer than i+ elements, the whole sequence is returned. O(\log(\min(i,n-i))) ). Elements of a sequence after the first i. If i is negative,  i s yields the whole sequence. If the sequence contains fewer than i+ elements, the empty sequence is returned. O(\log(\min(i,n-i))) ). Split a sequence at a given position.  i s = ( i s,  i s).  O(\log(\min(i,n-i)))  A version of  that does not attempt to enhance sharing when the split point is less than or equal to 0, and that gives completely wrong answers when the split point is at least the length of the sequence, unless the sequence is a singleton. This is used to implement zipWith and chunksOf, which are extremely sensitive to the cost of splitting very short sequences. There is just enough of a speed increase to make this worth the trouble. containers,O \Bigl(\bigl(\frac{n}{c}\bigr) \log c\Bigr).  chunksOf c xs splits xs into chunks of size c>0. If c does not divide the length of xs< evenly, then the last element of the result will be short.Side note: the given performance bound is missing some messy terms that only really affect edge cases. Performance degrades smoothly from  O(1)  (for  c = n ) to  O(n)  (for  c = 1  ). The true bound is more like  O \Bigl( \bigl(\frac{n}{c} - 1\bigr) (\log (c + 1)) + 1 \Bigr)  O(n) . Returns a sequence of all suffixes of this sequence, longest first. For example, tails (fromList "abc") = fromList [fromList "abc", fromList "bc", fromList "c", fromList ""]Evaluating the  i th suffix takes  O(\log(\min(i, n-i))) 5, but evaluating every suffix in the sequence takes  O(n)  due to sharing. O(n) . Returns a sequence of all prefixes of this sequence, shortest first. For example, inits (fromList "abc") = fromList [fromList "", fromList "a", fromList "ab", fromList "abc"]Evaluating the  i th prefix takes  O(\log(\min(i, n-i))) 5, but evaluating every prefix in the sequence takes  O(n)  due to sharing. Given a function to apply to tails of a tree, applies that function to every tail of the specified tree. Given a function to apply to inits of a tree, applies that function to every init of the specified tree. is a version of 9 that also provides access to the index of each element. is a version of  9 that also provides access to the index of each element. O(i)  where  i  is the prefix length. , applied to a predicate p and a sequence xs2, returns the longest prefix (possibly empty) of xs of elements that satisfy p. O(i)  where  i  is the suffix length. , applied to a predicate p and a sequence xs2, returns the longest suffix (possibly empty) of xs of elements that satisfy p. p xs is equivalent to  ( p ( xs)). O(i)  where  i  is the prefix length.  p xs% returns the suffix remaining after  p xs. O(i)  where  i  is the suffix length.  p xs% returns the prefix remaining after  p xs. p xs is equivalent to  ( p ( xs)). O(i)  where  i  is the prefix length. , applied to a predicate p and a sequence xs, returns a pair whose first element is the longest prefix (possibly empty) of xs of elements that satisfy p9 and the second element is the remainder of the sequence. O(i)  where  i  is the suffix length. , applied to a predicate p and a sequence xs, returns a pair whose first element is the longest suffix (possibly empty) of xs of elements that satisfy p9 and the second element is the remainder of the sequence. O(i)  where  i  is the breakpoint index. , applied to a predicate p and a sequence xs, returns a pair whose first element is the longest prefix (possibly empty) of xs of elements that do not satisfy p: and the second element is the remainder of the sequence. p is equivalent to  (not . p). p is equivalent to  (not . p). O(n) . The  function takes a predicate p and a sequence xs and returns sequences of those elements which do and do not satisfy the predicate. O(n) . The  function takes a predicate p and a sequence xs and returns a sequence of those elements which satisfy the predicate. finds the leftmost index of the specified element, if it is present, and otherwise  . finds the rightmost index of the specified element, if it is present, and otherwise  . finds the indices of the specified element, from left to right (i.e. in ascending order). finds the indices of the specified element, from right to left (i.e. in descending order). p xs9 finds the index of the leftmost element that satisfies p, if any exist. p xs: finds the index of the rightmost element that satisfies p, if any exist. p, finds all indices of elements that satisfy p, in ascending order. p, finds all indices of elements that satisfy p, in descending order. O(n) . Create a sequence from a finite list of elements. There is a function  5 in the opposite direction for all instances of the   class, including . O(n) . The reverse of a sequence.  O(n) . Reverse a sequence while mapping over it. This is not currently exported, but is used in rewrite rules.  O(n) . Constructs a new sequence with the same structure as an existing sequence using a user-supplied mapping function along with a splittable value and a way to split it. The value is split up lazily according to the structure of the sequence, so one piece of the value is distributed to each element of the sequence. The caller should provide a splitter function that takes a number, n5, and a splittable value, breaks off a chunk of size n from the value, and returns that chunk and the remainder as a pair. The following examples will hopefully make the usage clear: zipWith :: (a -> b -> c) -> Seq a -> Seq b -> Seq c zipWith f s1 s2 = splitMap splitAt (\b a -> f a (b `index` 0)) s2' s1' where minLen = min (length s1) (length s2) s1' = take minLen s1 s2' = take minLen s2 mapWithIndex :: (Int -> a -> b) -> Seq a -> Seq b mapWithIndex f = splitMap (\n i -> (i, n+i)) f 0 containers Unzip a sequence of pairs. unzip ps = ps   (   ps) (   ps) Example: unzip $ fromList [(1,"a"), (2,"b"), (3,"c")] = (fromList [1,2,3], fromList ["a", "b", "c"]) !See the note about efficiency at . containers  O(n) 7. Unzip a sequence using a function to divide elements.  unzipWith f xs ==  (  f xs)Efficiency note: unzipWith9 produces its two results in lockstep. If you calculate  unzipWith f xs  and fully force either3 of the results, then the entire structure of the other one will be built as well. This behavior allows the garbage collector to collect each calculated pair component as soon as it dies, without having to wait for its mate to die. If you do not need this behavior, you may be better off simply calculating the sequence of pairs and using  % to extract each component sequence. O(\min(n_1,n_2)) .  takes two sequences and returns a sequence of corresponding pairs. If one input is short, excess elements are discarded from the right end of the longer sequence. O(\min(n_1,n_2)) .  generalizes  by zipping with the function given as the first argument, instead of a tupling function. For example,  zipWith (+) is applied to two sequences to take the sequence of corresponding sums. A version of zipWith that assumes the sequences have the same length. O(\min(n_1,n_2,n_3)) .  takes three sequences and returns a sequence of triples, analogous to . O(\min(n_1,n_2,n_3)) .  takes a function which combines three elements, as well as three sequences and returns a sequence of their point-wise combinations, analogous to . O(\min(n_1,n_2,n_3,n_4)) .  takes four sequences and returns a sequence of quadruples, analogous to . O(\min(n_1,n_2,n_3,n_4)) .  takes a function which combines four elements, as well as four sequences and returns a sequence of their point-wise combinations, analogous to . fromList2, given a list and its length, constructs a completely balanced Seq whose elements are that list using the replicateA generalization. containers     =     =  containers containers containers  containers  containers  containers  containers containers containers  containers containers containers containers containers containers  containers  containers  containers  containers  containers  containers  containers  containers  containers  containers  containers  containers  ffirstx flastx f midxsRigid s pr m sf (pr : prefix, sf : suffix)3333333  Safe-InferredIA pairing heap tagged with both a key and the original position of its elements, for use in .A pairing heap tagged with some key for sorting elements, for use in .A pairing heap tagged with the original position of elements, to allow for stable sorting.A simple pairing heap. containers O(n \log n) .  sorts the specified  by the natural ordering of its elements. The sort is stable. If stability is not required,  can be slightly faster. containers O(n \log n) .  sorts the specified  according to the specified comparator. The sort is stable. If stability is not required,  can be slightly faster. containers  O(n \log n) .  sorts the specified  by comparing the results of a key function applied to each element.  f is equivalent to  (  45 f)8, but has the performance advantage of only evaluating f once for each element in the input list. This is called the decorate-sort-undecorate paradigm, or Schwartzian transform.An example of using  might be to sort a ' of strings according to their length: sortOn length (fromList ["alligator", "monkey", "zebra"]) == fromList ["zebra", "monkey", "alligator"] If, instead,  had been used,  1 would be evaluated on every comparison, giving  O(n \log n)  evaluations, rather than  O(n) .If f2 is very cheap (for example a record selector, or ),  (  45 f) will be faster than  f. O(n \log n) .  sorts the specified  by the natural ordering of its elements, but the sort is not stable. This algorithm is frequently faster and uses less memory than . containers O(n \log n) . A generalization of ,  takes an arbitrary comparator and sorts the specified sequence. The sort is not stable. This algorithm is frequently faster and uses less memory than . containers  O(n \log n) .  sorts the specified  by comparing the results of a key function applied to each element.  f is equivalent to  (  45 f)8, but has the performance advantage of only evaluating f once for each element in the input list. This is called the decorate-sort-undecorate paradigm, or Schwartzian transform.An example of using  might be to sort a ' of strings according to their length: unstableSortOn length (fromList ["alligator", "monkey", "zebra"]) == fromList ["zebra", "monkey", "alligator"] If, instead,  had been used,  1 would be evaluated on every comparison, giving  O(n \log n)  evaluations, rather than  O(n) .If f2 is very cheap (for example a record selector, or ),  (  45 f) will be faster than  f. merges two s. merges two s, based on the tag value. merges two >s, taking into account the original position of the elements. merges two s, based on the tag value, taking into account the original position of the elements.Pop the smallest element from the queue, using the supplied comparator.Pop the smallest element from the queue, using the supplied comparator, deferring to the item's original position when the comparator returns  .Pop the smallest element from the queue, using the supplied comparator on the tag.Pop the smallest element from the queue, using the supplied comparator on the tag, deferring to the item's original position when the comparator returns  .A  $-like function, specialized to the 67= monoid, which takes advantage of the internal structure of  to avoid wrapping in   at certain points.A 8$-like function, specialized to the 67= monoid, which takes advantage of the internal structure of  to avoid wrapping in   at certain points.(((c) Ross Paterson 2005 (c) Louis Wasserman 2009 (c) Bertram Felgenhauer, David Feuer, Ross Paterson, and Milan Straka 2014 BSD-stylelibraries@haskell.orgportable Safe-Inferred "(c) The University of Glasgow 2002/BSD-style (see the file libraries/base/LICENSE)libraries@haskell.orgportable Trustworthy8=;This type synonym exists primarily for historical reasons.=Non-empty, possibly infinite, multi-way trees; also known as  rose trees.zero or more child trees label value&2-dimensional ASCII drawing of a tree.Examples =putStr $ drawTree $ fmap show (Node 1 [Node 2 [], Node 3 []]) 1 | +- 2 | `- 3 (2-dimensional ASCII drawing of a forest.Examples putStr $ drawForest $ map (fmap show) [(Node 1 [Node 2 [], Node 3 []]), (Node 10 [Node 20 []])] 1 | +- 2 | `- 3 10 | `- 20 ,Returns the elements of a tree in pre-order.  a / \ => [a,b,c] b c Examples 2flatten (Node 1 [Node 2 [], Node 3 []]) == [1,2,3]4Returns the list of nodes at each level of the tree. # a / \ => [[a], [b,c]] b c Examples 5levels (Node 1 [Node 2 [], Node 3 []]) == [[1],[2,3]] containers8Fold a tree into a "summary" value in depth-first order.!For each node in the tree, apply f to the  rootLabel and the result of applying f to each  subForest.0This is also known as the catamorphism on trees.ExamplesSum the values in a tree: foldTree (\x xs -> sum (x:xs)) (Node 1 [Node 2 [], Node 3 []]) == 6#Find the maximum value in the tree: foldTree (\x xs -> maximum (x:xs)) (Node 1 [Node 2 [], Node 3 []]) == 3'Count the number of leaves in the tree: foldTree (\_ xs -> if null xs then 1 else sum xs) (Node 1 [Node 2 [], Node 3 []]) == 2Find depth of the tree; i.e. the number of branches from the root of the tree to the furthest leaf: foldTree (\_ xs -> if null xs then 0 else 1 + maximum xs) (Node 1 [Node 2 [], Node 3 []]) == 1/You can even implement traverse using foldTree: traverse' f = foldTree (\x xs -> liftA2 Node (f x) (sequenceA xs))Build a (possibly infinite) tree from a seed value in breadth-first order.unfoldTree f b. constructs a tree by starting with the tree "Node { rootLabel=b, subForest=[] } and repeatedly applying f to each , value in the tree's leaves to generate its .For a monadic version see .ExamplesConstruct the tree of Integer%s where each node has two children:  left = 2*x and right = 2*x + 1, where x is the - of the node. Stop when the values exceed 7. let buildNode x = if 2*x + 1 > 7 then (x, []) else (x, [2*x, 2*x+1]) putStr $ drawTree $ fmap show $ unfoldTree buildNode 1  1 | +- 2 | | | +- 4 | | | `- 5 | `- 3 | +- 6 | `- 7 Build a (possibly infinite) forest from a list of seed values in breadth-first order.unfoldForest f seeds invokes  on each seed value.For a monadic version see .+Monadic tree builder, in depth-first order.,Monadic forest builder, in depth-first order-Monadic tree builder, in breadth-first order.See  for more info.-Implemented using an algorithm adapted from Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design, by Chris Okasaki, ICFP'00..Monadic forest builder, in breadth-first orderSee  for more info.-Implemented using an algorithm adapted from Breadth-First Numbering: Lessons from a Small Exercise in Algorithm Design, by Chris Okasaki, ICFP'00. containers  containersFolds in preorderFolds in preorder containers  containers  containers  containers  containers  containers containers  containers  containers "(c) The University of Glasgow 2002/BSD-style (see the file libraries/base/LICENSE)libraries@haskell.orgportableSafe (78=,,An edge from the first vertex to the second.The bounds of an Array.Adjacency list representation of a graph, mapping each vertex to its list of successors..Table indexed by a contiguous set of vertices.3Note: This is included for backwards compatibility.$Abstract representation of vertices.Strongly connected component.)A single vertex that is not in any cycle. containers-A maximal set of mutually reachable vertices.8Partial pattern synonym for backward compatibility with containers < 0.7.8The vertices of a list of strongly connected components./The vertices of a strongly connected component.O((V+E) \log V). The strongly connected components of a directed graph, reverse topologically sorted.Examples stronglyConnComp [("a",0,[1]),("b",1,[2,3]),("c",2,[1]),("d",3,[3])] == [CyclicSCC ["d"],CyclicSCC ["b","c"],AcyclicSCC "a"]O((V+E) \log V). The strongly connected components of a directed graph, reverse topologically sorted. The function is the same as , except that all the information about each node retained. This interface is used when you expect to apply  to (some of) the result of 8, so you don't want to lose the dependency information.Examples stronglyConnCompR [("a",0,[1]),("b",1,[2,3]),("c",2,[1]),("d",3,[3])] == [CyclicSCC [("d",3,[3])],CyclicSCC [("b",1,[2,3]),("c",2,[1])],AcyclicSCC ("a",0,[1])]O(V),. Returns the list of vertices in the graph.Examples !vertices (buildG (0,-1) []) == [] 0vertices (buildG (0,2) [(0,1),(1,2)]) == [0,1,2]O(V+E)). Returns the list of edges in the graph.Examples edges (buildG (0,-1) []) == [] 3edges (buildG (0,2) [(0,1),(1,2)]) == [(0,1),(1,2)]O(V+E)%. Build a graph from a list of edges.Warning: This function will cause a runtime exception if a vertex in the edge list is not within the given Bounds.Examples buildG (0,-1) [] == array (0,-1) [] buildG (0,2) [(0,1), (1,2)] == array (0,1) [(0,[1]),(1,[2])] buildG (0,2) [(0,1), (0,2), (1,2)] == array (0,2) [(0,[2,1]),(1,[2]),(2,[])]O(V+E),. The graph obtained by reversing all edges.Examples transposeG (buildG (0,2) [(0,1), (1,2)]) == array (0,2) [(0,[]),(1,[0]),(2,[1])]O(V+E)/. A table of the count of edges from each node.Examples /outdegree (buildG (0,-1) []) == array (0,-1) [] outdegree (buildG (0,2) [(0,1), (1,2)]) == array (0,2) [(0,1),(1,1),(2,0)]O(V+E)/. A table of the count of edges into each node.Examples .indegree (buildG (0,-1) []) == array (0,-1) [] indegree (buildG (0,2) [(0,1), (1,2)]) == array (0,2) [(0,0),(1,1),(2,1)]O((V+E) \log V). Identical to , except that the return value does not include the function which maps keys to vertices. This version of  is for backwards compatibility.O((V+E) \log V). Build a graph from a list of nodes uniquely identified by keys, with a list of keys of nodes this node should have edges to.This function takes an adjacency list representing a graph with vertices of type key labeled by values of type node and produces a Graph)-based representation of that list. The Graph result represents the shape of the graph, and the functions describe a) how to retrieve the label and adjacent vertices of a given vertex, and b) how to retrieve a vertex given a key. (graph, nodeFromVertex, vertexFromKey) = graphFromEdges edgeListgraph :: Graph6 is the raw, array based adjacency list for the graph..nodeFromVertex :: Vertex -> (node, key, [key])7 returns the node associated with the given 0-based Int vertex; see warning below. This runs in O(1) time.$vertexFromKey :: key -> Maybe Vertex returns the Int2 vertex for the key if it exists in the graph, Nothing otherwise. This runs in  O(\log V) time.To safely use this API you must either extract the list of vertices directly from the graph or first call vertexFromKey k. to check if a vertex corresponds to the key k5. Once it is known that a vertex exists you can use nodeFromVertex to access the labelled node and adjacent vertices. See below for examples.Note: The out-list may contain keys that don't correspond to nodes of the graph; they are ignored. Warning: The nodeFromVertex7 function will cause a runtime exception if the given Vertex does not exist.ExamplesAn empty graph. (graph, nodeFromVertex, vertexFromKey) = graphFromEdges [] graph = array (0,-1) []9A graph where the out-list references unspecified nodes ('c'), these are ignored. (graph, _, _) = graphFromEdges [("a", 'a', ['b']), ("b", 'b', ['c'])] array (0,1) [(0,[1]),(1,[])]0A graph with 3 vertices: ("a") -> ("b") -> ("c") (graph, nodeFromVertex, vertexFromKey) = graphFromEdges [("a", 'a', ['b']), ("b", 'b', ['c']), ("c", 'c', [])] graph == array (0,2) [(0,[1]),(1,[2]),(2,[])] nodeFromVertex 0 == ("a",'a',"b") vertexFromKey 'a' == Just 0Get the label for a given key. let getNodePart (n, _, _) = n (graph, nodeFromVertex, vertexFromKey) = graphFromEdges [("a", 'a', ['b']), ("b", 'b', ['c']), ("c", 'c', [])] getNodePart . nodeFromVertex <$> vertexFromKey 'a' == Just "A"O(V+E). A spanning forest of the graph, obtained from a depth-first search of the graph starting from each vertex in an unspecified order.O(V+E). A spanning forest of the part of the graph reachable from the listed vertices, obtained from a depth-first search of the graph starting at each of the listed vertices in order.O(V+E). A topological sort of the graph. The order is partially specified by the condition that a vertex i precedes j whenever j is reachable from i but not vice versa.Note: A topological sort exists only when there are no cycles in the graph. If the graph has cycles, the output of this function will not be a topological sort. In such a case consider using . containersO(V+E). Reverse ordering of . See note in .O(V+E). The connected components of a graph. Two vertices are connected if there is a path between them, traversing edges in either direction.O(V+E). The strongly connected components of a graph, in reverse topological order.Examples scc (buildG (0,3) [(3,1),(1,2),(2,0),(0,1)]) == [Node {rootLabel = 0, subForest = [Node {rootLabel = 1, subForest = [Node {rootLabel = 2, subForest = []}]}]} ,Node {rootLabel = 3, subForest = []}]O(V+E)=. Returns the list of vertices reachable from a given vertex.Examples $reachable (buildG (0,0) []) 0 == [0] 4reachable (buildG (0,2) [(0,1), (1,2)]) 0 == [0,1,2]O(V+E) . Returns True/ if the second vertex reachable from the first.Examples "path (buildG (0,0) []) 0 0 == True .path (buildG (0,2) [(0,1), (1,2)]) 0 2 == True /path (buildG (0,2) [(0,1), (1,2)]) 2 0 == FalseO(V+E). The biconnected components of a graph. An undirected graph is biconnected if the deletion of any vertex leaves it connected.The input graph is expected to be undirected, i.e. for every edge in the graph the reverse edge is also in the graph. If the graph is not undirected the output is arbitrary. containers containers  containers containers  containers  containers  containers  containers  containers  containers  containers containers  containers  containers The graph: a list of nodes uniquely identified by keys, with a list of keys of nodes this node has edges to. The out-list may contain keys that don't correspond to nodes of the graph; such edges are ignored.The graph: a list of nodes uniquely identified by keys, with a list of keys of nodes this node has edges to. The out-list may contain keys that don't correspond to nodes of the graph; such edges are ignored.Reverse topologically sorted!"(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportable Trustworthy 7ӆ containers 7A tactic for dealing with keys present in both maps in .A tactic of type  SimpleWhenMatched k x y z 6 is an abstract representation of a function of type  k -> x -> y -> Maybe z . containers 8A tactic for dealing with keys present in both maps in  or .A tactic of type  WhenMatched f k x y z 6 is an abstract representation of a function of type  k -> x -> y -> f (Maybe z) . containers A tactic for dealing with keys present in one map but not the other in .A tactic of type  SimpleWhenMissing k x z 6 is an abstract representation of a function of type  k -> x -> Maybe z . containers A tactic for dealing with keys present in one map but not the other in  or .A tactic of type  WhenMissing f k x z 6 is an abstract representation of a function of type  k -> x -> f (Maybe z) .A Map from keys k to values a.The   operation for  is 2, which prefers values from the left operand. If m1 maps a key k to a value a1, and m2( maps the same key to a different value a2, then their union m1 <> m2 maps k to a1. O(\log n)". Find the value at a key. Calls # when the element can not be found. fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map fromList [(5,'a'), (3,'b')] ! 5 == 'a' containers  O(\log n)$. Find the value at a key. Returns  # when the element can not be found.-fromList [(5, 'a'), (3, 'b')] !? 1 == Nothing.fromList [(5, 'a'), (3, 'b')] !? 5 == Just 'a'Same as .O(1). Is the map empty? Data.Map.null (empty) == True Data.Map.null (singleton 1 'a') == FalseO(1)$. The number of elements in the map. size empty == 0 size (singleton 1 'a') == 1 size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3 O(\log n)'. Lookup the value at a key in the map.4The function will return the corresponding value as (  value), or   if the key isn't in the map.An example of using lookup: import Prelude hiding (lookup) import Data.Map employeeDept = fromList([("John","Sales"), ("Bob","IT")]) deptCountry = fromList([("IT","USA"), ("Sales","France")]) countryCurrency = fromList([("USA", "Dollar"), ("France", "Euro")]) employeeCurrency :: String -> Maybe String employeeCurrency name = do dept <- lookup name employeeDept country <- lookup dept deptCountry lookup country countryCurrency main = do putStrLn $ "John's currency: " ++ (show (employeeCurrency "John")) putStrLn $ "Pete's currency: " ++ (show (employeeCurrency "Pete"))The output of this program: 9 John's currency: Just "Euro" Pete's currency: Nothing O(\log n)+. Is the key a member of the map? See also . member 5 (fromList [(5,'a'), (3,'b')]) == True member 1 (fromList [(5,'a'), (3,'b')]) == False O(\log n)/. Is the key not a member of the map? See also . notMember 5 (fromList [(5,'a'), (3,'b')]) == False notMember 1 (fromList [(5,'a'), (3,'b')]) == True  O(\log n)". Find the value at a key. Calls # when the element can not be found. O(\log n). The expression ( def k map) returns the value at key k or returns default value def! when the key is not in the map. findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x' findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a' O(\log n). 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') O(\log n). 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')]) == Nothing O(\log n). 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') O(\log n). 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')]) == NothingO(1). The empty map. )empty == fromList [] size empty == 0O(1). A map with a single element. singleton 1 'a' == fromList [(1, 'a')] size (singleton 1 'a') == 1 O(\log n). Insert a new key and value in the map. If the key is already present in the map, the associated value is replaced with the supplied value.  is equivalent to  . 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' O(\log n)>. Insert with a function, combining new value and old value.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key, 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 . A helper function for . When the key is already in the map, the key is left alone, not replaced. The combining function is flipped--it is applied to the old value and then the new value.!Also see the performance note on . O(\log n). Insert with a function, combining key, new value and old value.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key,f key new_value old_value);. Note that the key passed to f is the same key passed to . 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 . A helper function for . When the key is already in the map, the key is left alone, not replaced. The combining function is flipped--it is applied to the old value and then the new value.!Also see the performance note on . O(\log n). Combines insert operation with old value retrieval. The expression ( f k x map2) is a pair where the first element is equal to ( k map$) and the second element equal to ( 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 . O(\log n). 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 == empty O(\log n). Update a value at a specific key with the result of the provided function. 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 == empty O(\log n). 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 == empty O(\log n). The expression ( f k map) updates the value x at k (if it is in the map). If (f x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\log n). The expression ( f k map) updates the value x at k (if it is in the map). If (f k x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\log n). Lookup and update. See also . The function returns changed value, if it is updated. 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 "5:new 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") O(\log n). The expression ( f k map) alters the value x at k, or absence thereof. 7 can be used to insert, delete, or update a value in a . In short :  k ( f k m) = f ( k m). let f _ = Nothing alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" let f _ = Just "c" alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")] alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")] Note that  = alter . fmap. containers O(\log n). The expression ( f k map) alters the value x at k, or absence thereof.  can be used to inspect, insert, delete, or update a value in a  . In short:  k <$>  f k m = f ( k m).Example: interactiveAlter :: Int -> Map Int String -> IO (Map Int String) interactiveAlter k m = alterF f k m where f Nothing = do putStrLn $ show k ++ " was not found in the map. Would you like to add it?" getUserResponse1 :: IO (Maybe String) f (Just old) = do putStrLn $ "The key is currently bound to " ++ show old ++ ". Would you like to change or delete it?" getUserResponse2 :: IO (Maybe String)  is the most general operation for working with an individual key that may or may not be in a given map. When used with trivial functors like  and  , it is often slightly slower than more specialized combinators like  and . However, when the functor is non-trivial and key comparison is not particularly cheap, it is the fastest way.Note on rewrite rules:3This module includes GHC rewrite rules to optimize  for the   and  functors. In general, these rules improve performance. The sole exception is that when using , deleting a key that is already absent takes longer than it would without the rules. If you expect this to occur a very large fraction of the time, you might consider using a private copy of the  type.Note:  is a flipped version of the at combinator from Control.Lens.At. O(\log n) . Return the index of a key, which is its zero-based index in the sequence sorted by keys. The index is a number from 0 up to, but not including, the  of the map. Calls  when the key is not a  of the map. findIndex 2 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map findIndex 3 (fromList [(5,"a"), (3,"b")]) == 0 findIndex 5 (fromList [(5,"a"), (3,"b")]) == 1 findIndex 6 (fromList [(5,"a"), (3,"b")]) Error: element is not in the map O(\log n) . Lookup the index of a key, which is its zero-based index in the sequence sorted by keys. The index is a number from 0 up to, but not including, the  of the map. isJust (lookupIndex 2 (fromList [(5,"a"), (3,"b")])) == False fromJust (lookupIndex 3 (fromList [(5,"a"), (3,"b")])) == 0 fromJust (lookupIndex 5 (fromList [(5,"a"), (3,"b")])) == 1 isJust (lookupIndex 6 (fromList [(5,"a"), (3,"b")])) == False O(\log n). Retrieve an element by its index, i.e. by its zero-based index in the sequence sorted by keys. If the index7 is out of range (less than zero, greater or equal to  of the map),  is called. elemAt 0 (fromList [(5,"a"), (3,"b")]) == (3,"b") elemAt 1 (fromList [(5,"a"), (3,"b")]) == (5, "a") elemAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range containers O(\log n). Take a given number of entries in key order, beginning with the smallest keys.  take n =  . '* n .   containers O(\log n). Drop a given number of entries in key order, beginning with the smallest keys.  drop n =  . '+ n .   containers O(\log n)$. Split a map at a particular index. splitAt !n !xs = ( n xs,  n xs)  O(\log n). Update the element at index, i.e. by its zero-based index in the sequence sorted by keys. If the index7 is out of range (less than zero, greater or equal to  of the map),  is called. updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")] updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")] updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range O(\log n). Delete the element at index, i.e. by its zero-based index in the sequence sorted by keys. If the index7 is out of range (less than zero, greater or equal to  of the map),  is called. deleteAt 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" deleteAt 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" deleteAt 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range deleteAt (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range containers  O(\log n)&. The minimal key of the map. Returns   if the map is empty. lookupMin (fromList [(5,"a"), (3,"b")]) == Just (3,"b") lookupMin empty = Nothing O(\log n)$. The minimal key of the map. Calls  if the map is empty. findMin (fromList [(5,"a"), (3,"b")]) == (3,"b") findMin empty Error: empty map has no minimal element containers  O(\log n)&. The maximal key of the map. Returns   if the map is empty. lookupMax (fromList [(5,"a"), (3,"b")]) == Just (5,"a") lookupMax empty = Nothing O(\log n)$. The maximal key of the map. Calls  if the map is empty. findMax (fromList [(5,"a"), (3,"b")]) == (5,"a") findMax empty Error: empty map has no maximal element O(\log n). Delete the minimal key. Returns an empty map if the map is empty. deleteMin (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(5,"a"), (7,"c")] deleteMin empty == empty O(\log n). Delete the maximal key. Returns an empty map if the map is empty. deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")] deleteMax empty == empty O(\log n)&. 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" O(\log n)&. 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" O(\log n)&. 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" O(\log n)&. 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" O(\log n). Retrieves the minimal (key,value) pair of the map, and the map stripped of that element, or   if passed an empty map. minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a") minViewWithKey empty == Nothing O(\log n). Retrieves the maximal (key,value) pair of the map, and the map stripped of that element, or   if passed an empty map. maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b") maxViewWithKey empty == Nothing O(\log n). Retrieves the value associated with minimal key of the map, and the map stripped of that element, or   if passed an empty map. minView (fromList [(5,"a"), (3,"b")]) == Just ("b", singleton 5 "a") minView empty == Nothing O(\log n). Retrieves the value associated with maximal key of the map, and the map stripped of that element, or   if passed an empty map. maxView (fromList [(5,"a"), (3,"b")]) == Just ("a", singleton 3 "b") maxView empty == Nothing!The 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")]=The union of a list of maps, with a combining operation: ( f == ') ( f) ). unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. The expression ( t1 t2!) takes the left-biased union of t1 and t2. It prefers t1- when duplicate keys are encountered, i.e. ( ==  ). union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n". 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 .=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n#. 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 .=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. Difference of two maps. Return elements of the first map not existing in the second map. difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b" containers=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. Remove all keys in a  from a . m `withoutKeys` s =  (\k _ -> k 9: s) m m `withoutKeys` s = m   (const ()) s O(n+m). Difference with a combining function. When two equal keys are encountered, the combining function is applied to the values of these keys. If it returns  , the element is discarded (proper set difference). If it returns (  y+), the element is updated with a new value y. 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"O(n+m). 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  , the element is discarded (proper set difference). If it returns (  y+), the element is updated with a new value y. 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"=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. Intersection of two maps. Return data in the first map for the keys existing in both maps. ( m1 m2 ==   m1 m2). intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a" containers=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n . Restrict a  to only those keys found in a . m `restrictKeys` s =  (\k _ -> k 9; s) m m `restrictKeys` s = m   (const ()) s =O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n). Intersection with a combining function. intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n). 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" containers=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. Check whether the key sets of two maps are disjoint (i.e., their  is empty). disjoint (fromList [(2,'a')]) (fromList [(1,()), (3,())]) == True disjoint (fromList [(2,'a')]) (fromList [(1,'a'), (2,'b')]) == False disjoint (fromList []) (fromList []) == True xs  ys = null (xs  ys)  containersRelate the keys of one map to the values of the other, by using the values of the former as keys for lookups in the latter. Complexity:  O (n * \log(m)) , 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")] ( bc ab ) = (bc  ) <=< (ab ) Note: Prior to v0.6.4, Data.Map.Strict exposed a version of & that forced the values of the output ,. This version does not force these values. containers Map covariantly over a  f k x.Map covariantly over a  f k x', using only a 'Functor f' constraint.Map covariantly over a  f k x', using only a 'Functor f' constraint. containers Map contravariantly over a  f k _ x. containers Map contravariantly over a  f k _ y z. containers Map contravariantly over a  f k x _ z. containers Along with zipWithMaybeAMatched, witnesses the isomorphism between WhenMatched f k x y z and k -> x -> y -> f (Maybe z). containers Along with traverseMaybeMissing, witnesses the isomorphism between WhenMissing f k x y and k -> x -> f (Maybe y). containers Map covariantly over a  f k x y. containers When a key is found in both maps, apply a function to the key and values and use the result in the merged map. zipWithMatched :: (k -> x -> y -> z) -> SimpleWhenMatched k x y z  containers When 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. containers When 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 :: (k -> x -> y -> Maybe z) -> SimpleWhenMatched k x y z  containers When 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  tactic. containers Drop all the entries whose keys are missing from the other map. 'dropMissing :: SimpleWhenMissing k x y /dropMissing = mapMaybeMissing (\_ _ -> Nothing)but  dropMissing is much faster. containers Preserve, unchanged, the entries whose keys are missing from the other map. +preserveMissing :: SimpleWhenMissing k x x =preserveMissing = Merge.Lazy.mapMaybeMissing (\_ x -> Just x)but preserveMissing is much faster. containers Force the entries whose keys are missing from the other map and otherwise preserve them unchanged. ,preserveMissing' :: SimpleWhenMissing k x x preserveMissing' = Merge.Lazy.mapMaybeMissing (\_ x -> Just $! x)but preserveMissing' is quite a bit faster. containers ?Map over the entries whose keys are missing from the other map. 7mapMissing :: (k -> x -> y) -> SimpleWhenMissing k x y 5mapMissing f = mapMaybeMissing (\k x -> Just $ f k x)but  mapMissing is somewhat faster. containers Map over the entries whose keys are missing from the other map, optionally removing some. This is the most powerful 0 tactic, but others are usually more efficient. mapMaybeMissing :: (k -> x -> Maybe y) -> SimpleWhenMissing k x y ?mapMaybeMissing f = traverseMaybeMissing (\k x -> pure (f k x))but mapMaybeMissing uses fewer unnecessary   operations. containers =Filter the entries whose keys are missing from the other map. =filterMissing :: (k -> x -> Bool) -> SimpleWhenMissing k x x filterMissing f = Merge.Lazy.mapMaybeMissing $ \k x -> guard (f k x) *> Just x#but this should be a little faster. containers Filter the entries whose keys are missing from the other map using some   action. filterAMissing f = Merge.Lazy.traverseMaybeMissing $ \k x -> (\b -> guard b *> Just x) <$> f k x#but this should be a little faster. :This wasn't in Data.Bool until 4.7.0, so we define it here containers Traverse over the entries whose keys are missing from the other map. containers Traverse over the entries whose keys are missing from the other map, optionally producing values to put in the result. This is the most powerful 0 tactic, but others are usually more efficient. containers Merge two maps. takes two  tactics, a  tactic and two maps. It uses the tactics to merge the maps. Its behavior is best understood via its fundamental tactics,  and .Consider merge (mapMaybeMissing g1) (mapMaybeMissing g2) (zipWithMaybeMatched f) m1 m2 Take, for example, m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] & will first "align" these maps by key: m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] It will then pass the individual entries and pairs of entries to g1, g2, or f as appropriate: maybes = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"] This produces a   for each key: keys = 0 1 2 3 4 results = [Nothing, Just True, Just False, Nothing, Just True]  Finally, the Just" results are collected into a map: 2return value = [(1, True), (2, False), (4, True)] The other tactics below are optimizations or simplifications of % for special cases. Most importantly, drops all the keys. leaves all the entries alone.When  is given three arguments, it is inlined at the call site. To prevent excessive inlining, you should typically use , to define your custom combining functions. Examples:unionWithKey f = merge preserveMissing preserveMissing (zipWithMatched f)intersectionWithKey f = merge dropMissing dropMissing (zipWithMatched f)differenceWith f = merge preserveMissing dropMissing (zipWithMatched f)symmetricDifference = merge preserveMissing preserveMissing (zipWithMaybeMatched $ \ _ _ _ -> Nothing)mapEachPiece f g h = merge (mapMissing f) (mapMissing g) (zipWithMatched h) containers An applicative version of . takes two  tactics, a  tactic and two maps. It uses the tactics to merge the maps. Its behavior is best understood via its fundamental tactics,  and .Consider mergeA (traverseMaybeMissing g1) (traverseMaybeMissing g2) (zipWithMaybeAMatched f) m1 m2 Take, for example, m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] mergeA& will first "align" these maps by key: m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] It will then pass the individual entries and pairs of entries to g1, g2, or f as appropriate: actions = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"] )Next, it will perform the actions in the actions# list in order from left to right. keys = 0 1 2 3 4 results = [Nothing, Just True, Just False, Nothing, Just True]  Finally, the Just" results are collected into a map: 2return value = [(1, True), (2, False), (4, True)] The other tactics below are optimizations or simplifications of % for special cases. Most importantly, drops all the keys. leaves all the entries alone. does not use the   context.When  is given three arguments, it is inlined at the call site. To prevent excessive inlining, you should generally only use & to define custom combining functions.O(n+m)'. An unsafe general combining function.WARNING: This function can produce corrupt maps and its results may depend on the internal structures of its inputs. Users should prefer  or .When  is given three arguments, it is inlined to the call site. You should therefore use  only to define custom combining functions. For example, you could define ,  and  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 m2 When calling  combine only1 only2, a function combining two s is created, such thatif 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  and  , but for example  f,  f, or  f could be used for any f.=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n . This function is defined as ( =  (==)).=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. The expression ( f t1 t2 ) returns   if all keys in t1 are in tree t2 , and when f returns   when applied to their respective values. For example, the following expressions are all  : isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])But the following are all  : isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)]) isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)]) Note that  isSubmapOfBy (_ _ -> True) m1 m2 tests whether all the keys in m1 are also keys in m2.=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. Is this a proper submap? (ie. a submap but not equal). Defined as ( =  (==)).=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n. Is this a proper submap? (ie. a submap but not equal). The expression ( f m1 m2 ) returns   when keys m1 and keys m2 are not equal, all keys in m1 are in m2 , and when f returns   when applied to their respective values. For example, the following expressions are all  : isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])But the following are all  : 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)])O(n)/. Filter all values that satisfy the 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")]) == emptyO(n)4. Filter all keys/values that satisfy the predicate. filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" O(n)". Filter keys and values using an   predicate. containers O(\log n). Take while a predicate on the keys holds. The user is responsible for ensuring that for all keys j and k in the map, j < k ==> p j >= p k. See note at . takeWhileAntitone p =  . ,- (p . fst) .  takeWhileAntitone p =  (k _ -> p k)  containers O(\log n). Drop while a predicate on the keys holds. The user is responsible for ensuring that for all keys j and k in the map, j < k ==> p j >= p k. See note at . dropWhileAntitone p =  . ,. (p . fst) .  dropWhileAntitone p =  (\k _ -> not (p k))  containers O(\log n). Divide a map at the point where a predicate on the keys stops holding. The user is responsible for ensuring that for all keys j and k in the map, j < k ==> p j >= p k. spanAntitone p xs = ( p xs, = 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 where the predicate switches from holding to not holding (where the predicate is seen to hold before the first key and to fail after the last key).O(n). Partition the map according to a predicate. The first map contains all elements that satisfy the predicate, the second all elements that fail the predicate. See also . 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")])O(n). Partition the map according to a predicate. The first map contains all elements that satisfy the predicate, the second all elements that fail the predicate. See also . 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")])O(n). Map values and collect the   results. let f x = if x == "a" then Just "new a" else Nothing mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"O(n)". Map keys/values and collect the   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" containersO(n)'. Traverse keys/values and collect the   results.O(n). Map values and separate the   and   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")])O(n)#. Map keys/values and separate the   and   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")])O(n),. Map a function over all values in the map. map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]O(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")]O(n).  f m ==  <$>   (\(k, v) -> (,) k <$> f k v) ( m)* That is, behaves exactly like a regular   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')]) == NothingO(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a b = (a ++ b, b ++ "X") mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])O(n). The function  threads an accumulating argument through the map in ascending order of keys. 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")]) O(n). The function   threads an accumulating argument through the map in ascending order of keys.O(n). The function  threads an accumulating argument through the map in descending order of keys. O(n \log n).  f s! is the map obtained by applying f to each key of s.)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" O(n \log n).  c f s! is the map obtained by applying f to each key of s.)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. The value at the greater of the two original keys is used as the first argument to 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 .O(n).  f s ==  f s, but works only when f2 is strictly monotonic. That is, for any values x and y, if x < y then f x < f y.  The precondition is not checked. 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 better performance than . mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")] valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True valid (mapKeysMonotonic (\ _ -> 1) (fromList [(5,"a"), (3,"b")])) == FalseO(n). Fold the values in the map using the given right-associative binary operator, such that  f z == '( f z . . For example, elems map = foldr (:) [] map let f a len = len + (length a) foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the values in the map using the given left-associative binary operator, such that  f z == ') f z . . For example, %elems = reverse . foldl (flip (:)) [] let f len a = len + (length a) foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the keys and values in the map using the given right-associative binary operator, such that  f z == '( ( f) z . . For example, 0keys map = foldrWithKey (\k x ks -> k:ks) [] map let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")" foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the keys and values in the map using the given left-associative binary operator, such that  f z == ') (\z' (kx, x) -> f z' kx x) z . . For example, 2keys = 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)"O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value. containersO(n). Fold the keys and values in the map using the given monoid, such that  f = '< .  f*This can be an asymptotically faster than  or  for some monoids.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 == []O(n). Return all keys of the map in ascending order. Subject to list fusion.  replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")] fromSet undefined Data.Set.empty == emptyO(n)6. Build a map from a set of elements contained inside  s. fromArgSet (Data.Set.fromList [Arg 3 "aaa", Arg 5 "aaaaa"]) == fromList [(5,"aaaaa"), (3,"aaa")] fromArgSet Data.Set.empty == empty O(n \log n)7. Build a map from a list of key/value pairs. See also . If the list contains more than one value for the same key, the last value for the key is retained.If the keys of the list are ordered, a linear-time implementation is used. 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")] O(n \log n). Build a map from a list of key/value pairs with a combining function. See also . 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. Performance!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 slow'because they evaluate as, respectively: fromList [(3, "x" ++ ("x" ++ "xxxxx..xxxxx"))] -- O(n) fromList [(3, ("xxxxx..xxxxx" ++ "x") ++ "x")] -- O(n)5Thus, 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")]7and it is always fast to combine singleton-list values [v] with fromListWith (++), as in: fromListWith (++) $ reverse $ map (\(k, v) -> (k, [v])) someListOfTuples O(n \log n). Build a map from a list of key/value pairs with a combining function. See also . 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 [] == empty!Also see the performance note on .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 == []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")]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")]O(n)6. Build a map from an ascending list in linear time. :The precondition (input list is ascending) is not checked. fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")] valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False containersO(n)6. Build a map from a descending list in linear time. ;The precondition (input list is descending) is not checked. fromDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")] fromDescList [(5,"a"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "b")] valid (fromDescList [(5,"a"), (5,"b"), (3,"b")]) == True valid (fromDescList [(5,"a"), (3,"b"), (5,"b")]) == FalseO(n). Build a map from an ascending list in linear time with a combining function for equal keys. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")] valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False containersO(n). Build a map from a descending list in linear time with a combining function for equal keys. ;The precondition (input list is descending) is not checked. fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "ba")] valid (fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")]) == True valid (fromDescListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False!Also see the performance note on .O(n). Build a map from an ascending list in linear time with a combining function for equal keys. :The precondition (input list is ascending) is not checked. let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2 fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")] valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False!Also see the performance note on .O(n). Build a map from a descending list in linear time with a combining function for equal keys. ;The precondition (input list is descending) is not checked. let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2 fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "5:b5:ba")] valid (fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")]) == True valid (fromDescListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False!Also see the performance note on .O(n). Build a map from an ascending list of distinct elements in linear time.  The precondition is not checked. fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False containersO(n). Build a map from a descending list of distinct elements in linear time.  The precondition is not checked. fromDistinctDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")] valid (fromDistinctDescList [(5,"a"), (3,"b")]) == True valid (fromDistinctDescList [(5,"a"), (5,"b"), (3,"b")]) == False O(\log n). The expression ( k map ) is a pair  (map1,map2) where the keys in map1 are smaller than k and the 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) O(\log n). The expression ( k map) splits a map just like  but also returns  k 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)  O(\log n). A variant of  that indicates only whether the key was present, rather than producing its value. This is used to implement ! to avoid allocating unnecessary   constructors. O(\log n)&. Delete and find the minimal element. deleteFindMin (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((3,"b"), fromList[(5,"a"), (10,"c")]) deleteFindMin empty Error: can not return the minimal element of an empty map O(\log n)&. Delete and find the maximal element. deleteFindMax (fromList [(5,"a"), (3,"b"), (10,"c")]) == ((10,"c"), fromList [(3,"b"), (5,"a")]) deleteFindMax empty Error: can not return the maximal element of an empty map containersO(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] ['a'..])) == [fromList [(1,'a'),(2,'b'),(3,'c')],fromList [(4,'d')],fromList [(5,'e'),(6,'f')]] splitRoot empty == []Note that the current implementation does not return more than three submaps, but you should not depend on this behaviour because it can change in the future without notice. containers!Folds in order of increasing key.%Traverses in order of increasing key. containers  containers  containers  containers  containers  containers  containers  containers containers Equivalent to " ReaderT k (ReaderT x (MaybeT f)) . containers Equivalent to " ReaderT k (ReaderT x (MaybeT f)) . containers  containers  containers Equivalent to . ReaderT k (ReaderT x (ReaderT y (MaybeT f)))  containers Equivalent to . ReaderT k (ReaderT x (ReaderT y (MaybeT f)))  containers  containers  containersWhat to do with keys in m1 but not m2What to do with keys in m2 but not m1What to do with keys in both m1 and m2Map m1Map m2What to do with keys in m1 but not m2What to do with keys in m2 but not m1What to do with keys in both m1 and m2Map m1Map m2   (c) David Feuer 2016 BSD-stylelibraries@haskell.orgportableSafe Safe-InferredJ O(n \log n). Show the tree that implements the map. The tree is shown in a compressed, hanging format. See . O(n \log n). The expression ( showelem hang wide map) shows the tree that implements the map. Elements are shown using the showElem function. If hang is  , a hanging6 tree is shown otherwise a rotated tree is shown. If wide is  !, an extra wide version is shown.  Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]] Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t (4,()) +--(2,()) | +--(1,()) | +--(3,()) +--(5,()) Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t (4,()) | +--(2,()) | | | +--(1,()) | | | +--(3,()) | +--(5,()) Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t +--(5,()) | (4,()) | | +--(3,()) | | +--(2,()) | +--(1,())O(n).. Test if the internal map structure is valid. valid (fromAscList [(3,"b"), (5,"a")]) == True valid (fromAscList [(5,"a"), (3,"b")]) == False'Test if the keys are ordered correctly.+Test if a map obeys the balance invariants.6Test if each node of a map reports its size correctly.  >(c) Daan Leijen 2002 (c) Joachim Breitner 2011 BSD-stylelibraries@haskell.orgportable Trustworthy 7t;A set of integers.O(n+m). See .O(1). Is the set empty?O(n). Cardinality of the set. O(\min(n,W))#. Is the value a member of the set? O(\min(n,W)) . Is the element not in the set? O(\min(n,W))2. Find largest element smaller than the given one. lookupLT 3 (fromList [3, 5]) == Nothing lookupLT 5 (fromList [3, 5]) == Just 3 O(\min(n,W))3. Find smallest element greater than the given one. lookupGT 4 (fromList [3, 5]) == Just 5 lookupGT 5 (fromList [3, 5]) == Nothing O(\min(n,W))9. 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 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]) == NothingO(1). The empty set.O(1). A set of one element. O(\min(n,W)). Add a value to the set. There is no left- or right bias for IntSets. O(\min(n,W)). Delete a value in the set. Returns the original set when the value was not present. containers O(\min(n,W)). ( f x s) can delete or insert x in s0 depending on whether it is already present in s. In short:  x <$>  f x s = f ( x s) Note:  is a variant of the at combinator from Control.Lens.At.The union of a list of sets.O(n+m). The union of two sets.O(n+m). Difference between two sets.O(n+m). The intersection of two sets.O(n+m)8. Is this a proper subset? (ie. a subset but not equal).O(n+m). Is this a subset? (s1 `isSubsetOf` s2) tells whether s1 is a subset of s2. containers O(n+m). 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 []) == TrueO(n)2. Filter all elements that satisfy some predicate.O(n)0. partition the set according to some predicate. containers 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 . takeWhileAntitone p =  . ,- p .  takeWhileAntitone p =  p  containers 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 . dropWhileAntitone p =  . ,. p .  dropWhileAntitone p =  (not . p)  containers 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 = ( p xs,  p xs) spanAntitone p xs =  p xs  Note: if p is not actually antitone, then  spanAntitone will split the set at some  unspecified point. O(\min(n,W)). The expression ( 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]) O(\min(n,W)) . Performs a  but also returns whether the pivot element was found in the original set. O(\min(n,W)). Retrieves the maximal key of the set, and the set stripped of that element, or   if passed an empty set. O(\min(n,W)). Retrieves the minimal key of the set, and the set stripped of that element, or   if passed an empty set. O(\min(n,W))&. Delete and find the minimal element. 0deleteFindMin set = (findMin set, deleteMin set) O(\min(n,W))&. Delete and find the maximal element. 0deleteFindMax set = (findMax set, deleteMax set) O(\min(n,W))!. The minimal element of the set. O(\min(n,W)). The maximal element of a set. 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 90 @ versions prior to 0.5 threw an error if the  was already empty. 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 90 @ versions prior to 0.5 threw an error if the  was already empty.O(n \min(n,W)).  f s! is the set obtained by applying f to each element of s.It's worth noting that the size of the result may be smaller if, for some (x,y), x /= y && f x == f y containersO(n). The f s ==  f s, but works only when f is strictly increasing.  The precondition is not checked. Semi-formally, we have: and [x < y ==> f x < f y | x <- ls, y <- ls] ==> mapMonotonic f s == map f s where ls = toList sO(n). Fold the elements in the set using the given right-associative binary operator. This function is an equivalent of ( and is present for compatibility only.Please note that fold will be deprecated in the future and removed.O(n). Fold the elements in the set using the given right-associative binary operator, such that  f z == '( f z . . For example,  toAscList set = foldr (:) [] setO(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the elements in the set using the given left-associative binary operator, such that  f z == ') f z . . For example, (toDescList set = foldl (flip (:)) [] setO(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). An alias of . The elements of a set in ascending order. Subject to list fusion.O(n). Convert the set to a list of elements. Subject to list fusion.O(n). Convert the set to an ascending list of elements. Subject to list fusion.O(n). Convert the set to a descending list of elements. Subject to list fusion.O(n \min(n,W))'. Create a set from a list of integers. containersO(n / W)(. Create a set from a range of integers. -fromRange (low, high) == fromList [low..high]O(n)3. Build a set from an ascending list of elements. :The precondition (input list is ascending) is not checked.O(n)<. Build a set from an ascending list of distinct elements. The precondition (input list is strictly ascending) is not checked. O(n)0. Build a set from a monotonic list of elements.The precise conditions under which this function works are subtle: For any branch mask, keys with the same prefix w.r.t. the branch mask must occur consecutively in the list.O(n \min(n,W)). Show the tree that implements the set. The tree is shown in a compressed, hanging format.O(n \min(n,W)). The expression ( hang wide map.) shows the tree that implements the set. If hang is  , a hanging6 tree is shown otherwise a rotated tree is shown. If wide is  !, an extra wide version is shown.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. containers containers containers >(c) Daan Leijen 2002 (c) Joachim Breitner 2011 BSD-stylelibraries@haskell.orgportableSafe88(c) Gershom Bazerman 2018 BSD-stylelibraries@haskell.orgportable Trustworthy - containers O(n \log d) . The nubOrd function removes duplicate elements from a list. In particular, it keeps only the first occurrence of each element. By using a 9 internally it has better asymptotics than the standard ,= function. StrictnessnubOrd' is strict in the elements of the list.Efficiency note3When applicable, it is almost always better to use  or  instead of this function, although it can be a little worse in certain pathological cases. For example, to nub a list of characters, use  nubIntOn fromEnum xs containersThe nubOrdOn function behaves just like  except it performs comparisons not on the original datatype, but a user-specified projection from that datatype. StrictnessnubOrdOn is strict in the values of the function applied to the elements of the list. containers O(n \min(d,W)) . The nubInt function removes duplicate   values from a list. In particular, it keeps only the first occurrence of each element. By using an > internally, it attains better asymptotics than the standard ,= function. See also *, a more widely applicable generalization. StrictnessnubInt' is strict in the elements of the list. containersThe nubIntOn function behaves just like  except it performs comparisons not on the original datatype, but a user-specified projection from that datatype. For example,  nubIntOn   can be used to nub characters and typical fixed-with numerical types efficiently. StrictnessnubIntOn is strict in the values of the function applied to the elements of the list.(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 (c) wren romano 2016 BSD-stylelibraries@haskell.orgportable Trustworthy 7( containers 7A tactic for dealing with keys present in both maps in .A tactic of type SimpleWhenMatched x y z6 is an abstract representation of a function of type Key -> x -> y -> Maybe z. containers 7A tactic for dealing with keys present in both maps in  or .A tactic of type WhenMatched f x y z6 is an abstract representation of a function of type Key -> x -> y -> f (Maybe z). containers A tactic for dealing with keys present in one map but not the other in .A tactic of type SimpleWhenMissing x z6 is an abstract representation of a function of type Key -> x -> Maybe z. containers A tactic for dealing with keys present in one map but not the other in  or .A tactic of type WhenMissing f k x z6 is an abstract representation of a function of type Key -> x -> f (Maybe z).A map of integers to values a. O(\min(n,W))". Find the value at a key. Calls # when the element can not be found. fromList [(5,'a'), (3,'b')] ! 1 Error: element not in the map fromList [(5,'a'), (3,'b')] ! 5 == 'a' containers  O(\min(n,W))$. Find the value at a key. Returns  # when the element can not be found. fromList [(5,'a'), (3,'b')] !? 1 == Nothing fromList [(5,'a'), (3,'b')] !? 5 == Just 'a'Same as .O(1). Is the map empty? Data.IntMap.null (empty) == True Data.IntMap.null (singleton 1 'a') == FalseO(n) . Number of elements in the map. size empty == 0 size (singleton 1 'a') == 1 size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3 O(\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')]) == False O(\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')]) == True O(\min(n,W))1. Lookup the value at a key in the map. See also >. O(\min(n,W)). The expression ( def k map) returns the value at key 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' 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') 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')]) == Nothing 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') 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')]) == Nothing containersO(n+m). Check whether the key sets of two maps are disjoint (i.e. their  is empty). disjoint (fromList [(2,'a')]) (fromList [(1,()), (3,())]) == True disjoint (fromList [(2,'a')]) (fromList [(1,'a'), (2,'b')]) == False disjoint (fromList []) (fromList []) == True 'disjoint a b == null (intersection a b) containersRelate the keys of one map to the values of the other, by using the values of the former as keys for lookups in the latter. 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")] ( bc ab ) = (bc  ) <=< (ab ) Note: Prior to v0.6.4, Data.IntMap.Strict exposed a version of & that forced the values of the output ,. This version does not force these values.O(1). The empty map. )empty == fromList [] size empty == 0O(1). A map of one element. singleton 1 'a' == fromList [(1, 'a')] size (singleton 1 'a') == 1 O(\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.  is equivalent to  . 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' O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp 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 . O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp 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 . O(\min(n,W)). The expression ( f k x map2) is a pair where the first element is equal to ( k map$) and the second element equal to ( 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 . O(\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 == empty O(\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 == empty O(\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 == empty O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f k x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\min(n,W)). Lookup and update. The function returns original value, if it is updated. This is different behavior than ?>. 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") O(\min(n,W)). The expression ( f k map) alters the value x at k, or absence thereof. 8 can be used to insert, delete, or update a value in an . In short :  k ( f k m) = f ( k m). containers O(\min(n,W)). The expression ( f k map) alters the value x at k, or absence thereof.  can be used to inspect, insert, delete, or update a value in an . In short :  k  $  f k m = f ( k m).Example: interactiveAlter :: Int -> IntMap String -> IO (IntMap String) interactiveAlter k m = alterF f k m where f Nothing = do putStrLn $ show k ++ " was not found in the map. Would you like to add it?" getUserResponse1 :: IO (Maybe String) f (Just old) = do putStrLn $ "The key is currently bound to " ++ show old ++ ". Would you like to change or delete it?" getUserResponse2 :: IO (Maybe String)  is the most general operation for working with an individual key that may or may not be in a given map.Note:  is a flipped version of the at combinator from Control.Lens.At.The 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")]8The 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")]O(n+m). The (left-biased) union of two maps. It prefers the first map when duplicate keys are encountered, i.e. ( ==  ). union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]O(n+m)&. 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 .O(n+m)&. 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 .O(n+m).. Difference between two maps (based on keys). difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"O(n+m)'. 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"O(n+m). 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  , the element is discarded (proper set difference). If it returns (  y+), the element is updated with a new value y. 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" containersO(n+m)0. Remove all the keys in a given set from a map. m `withoutKeys` s =  (\k _ -> k @: s) m O(n+m)=. The (left-biased) intersection of two maps (based on keys). intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a" containersO(n+m)0. The restriction of a map to the keys in a set. m `restrictKeys` s =  (\k _ -> k @; s) m  O(\min(n,W))?. Restrict to the sub-map with all keys matching a key prefix.O(n+m)-. The intersection with a combining function. intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"O(n+m)-. 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"O(n+m):. A high-performance universal combining function. Using , all combining functions can be defined without any loss of efficiency (with exception of ,  and ,, where sharing of some nodes is lost with ).6Please make sure you know what is going on when using , otherwise you can be surprised by unexpected code growth or even corruption of the data structure.When  is given three arguments, it is inlined to the call site. You should therefore use  only to define your custom combining functions. For example, you could define ,  and  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 m2 When calling  combine only1 only2, a function combining two s is created, such thatif 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  and  , but for example  f or  f could be used for any f. containers Map covariantly over a  f x.Map covariantly over a  f x', using only a 'Functor f' constraint.Map covariantly over a  f k x', using only a 'Functor f' constraint. containers Map contravariantly over a  f _ x. containers Map contravariantly over a  f _ y z. containers Map contravariantly over a  f x _ z. containers Along with zipWithMaybeAMatched, witnesses the isomorphism between WhenMatched f x y z and Key -> x -> y -> f (Maybe z). containers Along with traverseMaybeMissing, witnesses the isomorphism between WhenMissing f x y and Key -> x -> f (Maybe y). containers Map covariantly over a  f x y. containers When 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 z containers When 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. containers When 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 z containers When 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  tactic. containers Drop all the entries whose keys are missing from the other map. $dropMissing :: SimpleWhenMissing x y/dropMissing = mapMaybeMissing (\_ _ -> Nothing)but  dropMissing is much faster. containers Preserve, unchanged, the entries whose keys are missing from the other map. (preserveMissing :: SimpleWhenMissing x x=preserveMissing = Merge.Lazy.mapMaybeMissing (\_ x -> Just x)but preserveMissing is much faster. containers ?Map over the entries whose keys are missing from the other map. 4mapMissing :: (k -> x -> y) -> SimpleWhenMissing x y5mapMissing f = mapMaybeMissing (\k x -> Just $ f k x)but  mapMissing is somewhat faster. containers Map over the entries whose keys are missing from the other map, optionally removing some. This is the most powerful / tactic, but others are usually more efficient. mapMaybeMissing :: (Key -> x -> Maybe y) -> SimpleWhenMissing x y?mapMaybeMissing f = traverseMaybeMissing (\k x -> pure (f k x))but mapMaybeMissing uses fewer unnecessary   operations. containers =Filter 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 x#but this should be a little faster. containers Filter the entries whose keys are missing from the other map using some   action. filterAMissing f = Merge.Lazy.traverseMaybeMissing $ \k x -> (\b -> guard b *> Just x) <$> f k x#but this should be a little faster. O(n)". Filter keys and values using an   predicate. :This wasn't in Data.Bool until 4.7.0, so we define it here containers Traverse over the entries whose keys are missing from the other map. containers Traverse over the entries whose keys are missing from the other map, optionally producing values to put in the result. This is the most powerful 0 tactic, but others are usually more efficient. containersO(n)'. Traverse keys/values and collect the   results. containers Merge two maps. takes two  tactics, a  tactic and two maps. It uses the tactics to merge the maps. Its behavior is best understood via its fundamental tactics,  and .Consider merge (mapMaybeMissing g1) (mapMaybeMissing g2) (zipWithMaybeMatched f) m1 m2 Take, for example, m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] & will first "align" these maps by key: m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] It will then pass the individual entries and pairs of entries to g1, g2, or f as appropriate: maybes = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"] This produces a   for each key: keys = 0 1 2 3 4 results = [Nothing, Just True, Just False, Nothing, Just True]  Finally, the Just" results are collected into a map: 2return value = [(1, True), (2, False), (4, True)] The other tactics below are optimizations or simplifications of % for special cases. Most importantly, drops all the keys. leaves all the entries alone.When  is given three arguments, it is inlined at the call site. To prevent excessive inlining, you should typically use + to define your custom combining functions. Examples:unionWithKey f = merge preserveMissing preserveMissing (zipWithMatched f)intersectionWithKey f = merge dropMissing dropMissing (zipWithMatched f)0differenceWith f = merge diffPreserve diffDrop fsymmetricDifference = merge diffPreserve diffPreserve (\ _ _ _ -> Nothing)mapEachPiece f g h = merge (diffMapWithKey f) (diffMapWithKey g) containers An applicative version of . takes two  tactics, a  tactic and two maps. It uses the tactics to merge the maps. Its behavior is best understood via its fundamental tactics,  and .Consider mergeA (traverseMaybeMissing g1) (traverseMaybeMissing g2) (zipWithMaybeAMatched f) m1 m2 Take, for example, m1 = [(0, 'a'), (1, 'b'), (3,'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] & will first "align" these maps by key: m1 = [(0, 'a'), (1, 'b'), (3, 'c'), (4, 'd')] m2 = [(1, "one"), (2, "two"), (4, "three")] It will then pass the individual entries and pairs of entries to g1, g2, or f as appropriate: actions = [g1 0 'a', f 1 'b' "one", g2 2 "two", g1 3 'c', f 4 'd' "three"] )Next, it will perform the actions in the actions# list in order from left to right. keys = 0 1 2 3 4 results = [Nothing, Just True, Just False, Nothing, Just True]  Finally, the Just" results are collected into a map: 2return value = [(1, True), (2, False), (4, True)] The other tactics below are optimizations or simplifications of % for special cases. Most importantly, drops all the keys. leaves all the entries alone. does not use the   context.When  is given three arguments, it is inlined at the call site. To prevent excessive inlining, you should generally only use & to define custom combining functions. O(\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" O(\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" O(\min(n,W)). Retrieves the maximal (key,value) pair of the map, and the map stripped of that element, or   if passed an empty map. maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b") maxViewWithKey empty == Nothing O(\min(n,W)). Retrieves the minimal (key,value) pair of the map, and the map stripped of that element, or   if passed an empty map. minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a") minViewWithKey empty == Nothing O(\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" O(\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" O(\min(n,W)). Retrieves the maximal key of the map, and the map stripped of that element, or   if passed an empty map. O(\min(n,W)). Retrieves the minimal key of the map, and the map stripped of that element, or   if passed an empty map. O(\min(n,W)). Delete and find the maximal element. This function throws an error if the map is empty. Use  if the map may be empty. O(\min(n,W)). Delete and find the minimal element. This function throws an error if the map is empty. Use  if the map may be empty. O(\min(n,W))&. The minimal key of the map. Returns   if the map is empty. O(\min(n,W))$. The minimal key of the map. Calls  if the map is empty. Use  if the map may be empty. O(\min(n,W))&. The maximal key of the map. Returns   if the map is empty. O(\min(n,W))$. The maximal key of the map. Calls  if the map is empty. Use  if the map may be empty. O(\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 10 @ versions prior to 0.5 threw an error if the  was already empty. O(\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 10 @ versions prior to 0.5 threw an error if the  was already empty.O(n+m). Is this a proper submap? (ie. a submap but not equal). Defined as ( =  (==)).O(n+m). Is this a proper submap? (ie. a submap but not equal). The expression ( f m1 m2 ) returns   when keys m1 and keys m2 are not equal, all keys in m1 are in m2 , and when f returns   when applied to their respective values. For example, the following expressions are all  : isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)]) isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])But the following are all  : 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)])O(n+m)!. Is this a submap? Defined as ( =  (==)).O(n+m). The expression ( f m1 m2 ) returns   if all keys in m1 are in m2 , and when f returns   when applied to their respective values. For example, the following expressions are all  : 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  : 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)])O(n),. Map a function over all values in the map. map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]O(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")]O(n).  f s ==   $   ((k, v) -> (,) k  $ f k v) ( m)* That is, behaves exactly like a regular   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')]) == NothingO(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a b = (a ++ b, b ++ "X") mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])O(n). The function  threads an accumulating argument through the map in ascending order of keys. 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")]) O(n). The function   threads an accumulating argument through the map in ascending order of keys.O(n). The function  threads an accumulating argument through the map in descending order of keys.O(n \min(n,W)).  f s! is the map obtained by applying f to each key of s.)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"O(n \min(n,W)).  c f s! is the map obtained by applying f to each key of s.)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 .O(n).  f s ==  f s, but works only when f2 is strictly monotonic. That is, for any values x and y, if x < y then f x < f y.  The precondition is not checked. 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 . mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]O(n)0. Filter 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")]) == emptyO(n)5. Filter all keys/values that satisfy some predicate. filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "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 . 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")])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 . 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")]) containers O(\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 . takeWhileAntitone p =  . ,- (p . fst) .  takeWhileAntitone p =  (\k _ -> p k)  containers O(\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 . dropWhileAntitone p =  . ,. (p . fst) .  dropWhileAntitone p =  (\k _ -> not (p k))  containers 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 = ( p xs,  p xs) spanAntitone p xs =  (\k _ -> p k) xs  Note: if p is not actually antitone, then  spanAntitone will split the map at some  unspecified point.O(n). Map values and collect the   results. let f x = if x == "a" then Just "new a" else Nothing mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"O(n)". Map keys/values and collect the   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"O(n). Map values and separate the   and   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")])O(n)#. Map keys/values and separate the   and   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")]) O(\min(n,W)). The expression ( k map ) is a pair  (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) O(\min(n,W)) . Performs a  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)O(n). Fold the values in the map using the given right-associative binary operator, such that  f z == '( f z . . For example, elems map = foldr (:) [] map let f a len = len + (length a) foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the values in the map using the given left-associative binary operator, such that  f z == ') f z . . For example, %elems = reverse . foldl (flip (:)) [] let f len a = len + (length a) foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the keys and values in the map using the given right-associative binary operator, such that  f z == '( ( f) z . . For example, 0keys map = foldrWithKey (\k x ks -> k:ks) [] map let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")" foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value.O(n). Fold the keys and values in the map using the given left-associative binary operator, such that  f z == ') (\z' (kx, x) -> f z' kx x) z . . For example, 2keys = 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)"O(n). A strict version of . Each application of the operator is evaluated before using the result in the next application. This function is strict in the starting value. containersO(n). Fold the keys and values in the map using the given monoid, such that  f = '< .  f*This can be an asymptotically faster than  or  for some monoids.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 == []O(n). Return all keys of the map in ascending order. Subject to list fusion.  replicate k 'a') (Data.IntSet.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")] fromSet undefined Data.IntSet.empty == emptyO(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 == []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")]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")]O(n \min(n,W)).. Create a map from a list of key/value pairs. 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")]O(n \min(n,W)). Build a map from a list of key/value pairs with a combining function. See also . 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. Performance!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 slow'because they evaluate as, respectively: fromList [(3, "x" ++ ("x" ++ "xxxxx..xxxxx"))] -- O(n) fromList [(3, ("xxxxx..xxxxx" ++ "x") ++ "x")] -- O(n)5Thus, 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")]7and it is always fast to combine singleton-list values [v] with fromListWith (++), as in: fromListWith (++) $ reverse $ map (\(k, v) -> (k, [v])) someListOfTuplesO(n \min(n,W)). Build a map from a list of key/value pairs with a combining function. See also fromAscListWithKey'. 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 [] == empty!Also see the performance note on .O(n). Build a map from a list of key/value pairs where the keys are in ascending order. fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]O(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. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]!Also see the performance note on .O(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. :The precondition (input list is ascending) is not checked. let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "5:b|a")]!Also see the performance note on .O(n). Build a map from a list of key/value pairs where the keys are in ascending order and all distinct. The precondition (input list is strictly ascending) is not checked. fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] O(n). Build a map from a list of key/value pairs with monotonic keys and a combining function.The precise conditions under which this function works are subtle: For any branch mask, keys with the same prefix w.r.t. the branch mask must occur consecutively in the list.!Also see the performance note on .-Should this key follow the left subtree of a  with switching bit m&? N.B., the answer is only valid when  match i p m is true. Does the key i differ from the prefix p& before getting to the switching bit m? Does the key i match the prefix p (up to but not including bit m)?The prefix of key i. up to (but not including) the switching bit m.The prefix of key i. up to (but not including) the switching bit m.5Does the left switching bit specify a shorter prefix?8The first switching bit where the two prefixes disagree.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.O(n \min(n,W)). Show the tree that implements the map. The tree is shown in a compressed, hanging format.O(n \min(n,W)). The expression ( hang wide map.) shows the tree that implements the map. If hang is  , a hanging6 tree is shown otherwise a rotated tree is shown. If wide is  !, an extra wide version is shown. containers  containers  containers  containers  containers%Traverses in order of increasing key.!Folds in order of increasing key. containers containers Equivalent to  ReaderT k (ReaderT x (MaybeT f)). containers Equivalent to  ReaderT k (ReaderT x (MaybeT f)). containers  containers  containers Equivalent to .ReaderT Key (ReaderT x (ReaderT y (MaybeT f))) containers Equivalent to .ReaderT Key (ReaderT x (ReaderT y (MaybeT f))) containers  containers  containersWhat to do with keys in m1 but not m2What to do with keys in m2 but not m1What to do with keys in both m1 and m2Map m1Map m2What to do with keys in m1 but not m2What to do with keys in m2 but not m1What to do with keys in both m1 and m2Map m1Map m2  (c) wren romano 2016 BSD-stylelibraries@haskell.orgportableSafe6 Safe-InferredASafe 1I The constraint Whoops s is unsatisfiable for every   s$. Trying to use a function with a Whoops s constraint will lead to a pretty type error explaining how to fix the problem.Example oldFunction :: Whoops "oldFunction is gone now. Use newFunction." => Int -> IntMap a -> IntMap a  B Safe-Inferred1This function has moved to C.This function has moved to D. (c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportable Trustworthy*> O(\log n). The expression ( def k map) returns the value at key k or returns default value def! when the key is not in the map. findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x' findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'O(1). A map with a single element. singleton 1 'a' == fromList [(1, 'a')] size (singleton 1 'a') == 1 O(\log n). Insert a new key and value in the map. If the key is already present in the map, the associated value is replaced with the supplied value.  is equivalent to  . 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' O(\log n)>. Insert with a function, combining new value and old value.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key, 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 . O(\log n). Insert with a function, combining key, new value and old value.  f key value mp) will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key,f key new_value old_value);. Note that the key passed to f is the same key passed to . 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 . O(\log n). Combines insert operation with old value retrieval. The expression ( f k x map2) is a pair where the first element is equal to ( k map$) and the second element equal to ( 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 . O(\log n). Update a value at a specific key with the result of the provided function. 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 == empty O(\log n). 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 == empty O(\log n). The expression ( f k map) updates the value x at k (if it is in the map). If (f x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\log n). The expression ( f k map) updates the value x at k (if it is in the map). If (f k x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\log n). Lookup and update. See also . The function returns changed value, if it is updated. 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 "5:new 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") O(\log n). The expression ( f k map) alters the value x at k, or absence thereof. 7 can be used to insert, delete, or update a value in a . In short :  k ( f k m) = f ( k m). let f _ = Nothing alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")] alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" let f _ = Just "c" alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")] alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")] Note that  = alter . fmap. containers O(\log n). The expression ( f k map) alters the value x at k, or absence thereof.  can be used to inspect, insert, delete, or update a value in a  . In short:  k <$>  f k m = f ( k m).Example: interactiveAlter :: Int -> Map Int String -> IO (Map Int String) interactiveAlter k m = alterF f k m where f Nothing = do putStrLn $ show k ++ " was not found in the map. Would you like to add it?" getUserResponse1 :: IO (Maybe String) f (Just old) = do putStrLn $ "The key is currently bound to " ++ show old ++ ". Would you like to change or delete it?" getUserResponse2 :: IO (Maybe String)  is the most general operation for working with an individual key that may or may not be in a given map. When used with trivial functors like  and  , it is often slightly slower than more specialized combinators like  and . However, when the functor is non-trivial and key comparison is not particularly cheap, it is the fastest way.Note on rewrite rules:3This module includes GHC rewrite rules to optimize  for the   and  functors. In general, these rules improve performance. The sole exception is that when using , deleting a key that is already absent takes longer than it would without the rules. If you expect this to occur a very large fraction of the time, you might consider using a private copy of the  type.Note:  is a flipped version of the at combinator from Control.Lens.At. O(\log n). Update the element at index. Calls  when an invalid index is used. updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")] updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")] updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a" updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b" updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range O(\log n)&. 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" O(\log n)&. 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" O(\log n)&. 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" O(\log n)&. 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"=The union of a list of maps, with a combining operation: ( f == ') ( f) ). unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])] == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n". 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 .=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n#. 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 .O(n+m). Difference with a combining function. When two equal keys are encountered, the combining function is applied to the values of these keys. If it returns  , the element is discarded (proper set difference). If it returns (  y+), the element is updated with a new value y. 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"O(n+m). 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  , the element is discarded (proper set difference). If it returns (  y+), the element is updated with a new value y. 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"=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n). Intersection with a combining function. intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"=O\bigl(m \log\bigl(\frac{n}{m}+1\bigr)\bigr), \; 0 < m \leq n). 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"Map covariantly over a  f k x.Map covariantly over a  f k x y.When 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 :: (k -> x -> y -> Maybe z) -> SimpleWhenMatched k x y z When 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  tactic.When 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.When a key is found in both maps, apply a function to the key and values and use the result in the merged map. zipWithMatched :: (k -> x -> y -> z) -> SimpleWhenMatched k x y z Map over the entries whose keys are missing from the other map, optionally removing some. This is the most powerful 0 tactic, but others are usually more efficient. mapMaybeMissing :: (k -> x -> Maybe y) -> SimpleWhenMissing k x y ?mapMaybeMissing f = traverseMaybeMissing (\k x -> pure (f k x))but mapMaybeMissing uses fewer unnecessary   operations.?Map over the entries whose keys are missing from the other map. 7mapMissing :: (k -> x -> y) -> SimpleWhenMissing k x y 5mapMissing f = mapMaybeMissing (\k x -> Just $ f k x)but  mapMissing is somewhat faster.Traverse over the entries whose keys are missing from the other map, optionally producing values to put in the result. This is the most powerful 0 tactic, but others are usually more efficient.Traverse over the entries whose keys are missing from the other map.O(n+m)). An unsafe universal combining function.WARNING: This function can produce corrupt maps and its results may depend on the internal structures of its inputs. Users should prefer E or F.When  is given three arguments, it is inlined to the call site. You should therefore use  only to define custom combining functions. For example, you could define ,  and  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 m2 When calling  combine only1 only2, a function combining two s is created, such thatif 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  and  , but for example  f or  f could be used for any f.O(n). Map values and collect the   results. let f x = if x == "a" then Just "new a" else Nothing mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"O(n)". Map keys/values and collect the   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" containersO(n)'. Traverse keys/values and collect the   results.O(n). Map values and separate the   and   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")])O(n)#. Map keys/values and separate the   and   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")])O(n),. Map a function over all values in the map. map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]O(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")]O(n).  f m ==  <$>  1 (\(k, v) -> (v' -> v' `seq` (k,v')) <$> f k v) ( m)* That is, it behaves much like a regular   except that the traversing function also has access to the key associated with a value and the values are forced before they are installed in the result map. 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')]) == NothingO(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a b = (a ++ b, b ++ "X") mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])O(n). The function  threads an accumulating argument through the map in ascending order of keys. 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")]) O(n). The function   threads an accumulating argument through the map in ascending order of keys.O(n). The function  threads an accumulating argument through the map in descending order of keys. O(n \log n).  c f s! is the map obtained by applying f to each key of s.)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. The value at the greater of the two original keys is used as the first argument to 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 .O(n). Build a map from a set of keys and a function which for each key computes its value. fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")] fromSet undefined Data.Set.empty == emptyO(n)6. Build a map from a set of elements contained inside  s. fromArgSet (Data.Set.fromList [Arg 3 "aaa", Arg 5 "aaaaa"]) == fromList [(5,"aaaaa"), (3,"aaa")] fromArgSet Data.Set.empty == empty O(n \log n)7. Build a map from a list of key/value pairs. See also . If the list contains more than one value for the same key, the last value for the key is retained.If the keys of the list are ordered, a linear-time implementation is used. 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")] O(n \log n). Build a map from a list of key/value pairs with a combining function. See also . 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. Performance!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 slow'because they evaluate as, respectively: fromList [(3, "x" ++ ("x" ++ "xxxxx..xxxxx"))] -- O(n) fromList [(3, ("xxxxx..xxxxx" ++ "x") ++ "x")] -- O(n)5Thus, 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")]7and it is always fast to combine singleton-list values [v] with fromListWith (++), as in: fromListWith (++) $ reverse $ map (\(k, v) -> (k, [v])) someListOfTuples O(n \log n). Build a map from a list of key/value pairs with a combining function. See also . 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 [] == empty!Also see the performance note on .O(n)6. Build a map from an ascending list in linear time. :The precondition (input list is ascending) is not checked. fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")] valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == FalseO(n)6. Build a map from a descending list in linear time. ;The precondition (input list is descending) is not checked. fromDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")] fromDescList [(5,"a"), (5,"b"), (3,"a")] == fromList [(3, "b"), (5, "b")] valid (fromDescList [(5,"a"), (5,"b"), (3,"b")]) == True valid (fromDescList [(5,"a"), (3,"b"), (5,"b")]) == FalseO(n). Build a map from an ascending list in linear time with a combining function for equal keys. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")] valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False!Also see the performance note on .O(n). Build a map from a descending list in linear time with a combining function for equal keys. ;The precondition (input list is descending) is not checked. fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "ba")] valid (fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")]) == True valid (fromDescListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False!Also see the performance note on .O(n). Build a map from an ascending list in linear time with a combining function for equal keys. :The precondition (input list is ascending) is not checked. let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2 fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")] valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False!Also see the performance note on .O(n). Build a map from a descending list in linear time with a combining function for equal keys. ;The precondition (input list is descending) is not checked. let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2 fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "5:b5:ba")] valid (fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")]) == True valid (fromDescListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False!Also see the performance note on .O(n). Build a map from an ascending list of distinct elements in linear time.  The precondition is not checked. fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == FalseO(n). Build a map from a descending list of distinct elements in linear time.  The precondition is not checked. fromDistinctDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")] valid (fromDistinctDescList [(5,"a"), (3,"b")]) == True valid (fromDistinctDescList [(5,"a"), (3,"b"), (3,"a")]) == False(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableSafe-(c) David Feuer 2016 BSD-stylelibraries@haskell.orgportableSafe06(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableSafe1(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableSafe150=This function is being removed and is no longer usable. Use G.=This function is being removed and is no longer usable. Use H.=This function is being removed and is no longer usable. Use I.=This function is being removed and is no longer usable. Use (.=This function is being removed and is no longer usable. Use .J Safe-Inferred16 has moved to C has moved to D(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableNoneF/ O(\min(n,W)). The expression ( def k map) returns the value at key 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'O(1). A map of one element. singleton 1 'a' == fromList [(1, 'a')] size (singleton 1 'a') == 1 O(\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.  is equivalent to  . 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' O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp 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 . O(\min(n,W))%. Insert with a combining function.  f key value mp) will insert the pair (key, value) into mp 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"7If the key exists in the map, this function is lazy in value but strict in the result of f.!Also see the performance note on . O(\min(n,W)). The expression ( f k x map2) is a pair where the first element is equal to ( k map$) and the second element equal to ( 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 . O(\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 == empty O(\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 == empty O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\min(n,W)). The expression ( f k map) updates the value x at k (if it is in the map). If (f k x) is  %, the element is deleted. If it is (  y ), the key k 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" O(\min(n,W)). Lookup and update. The function returns original value, if it is updated. This is different behavior than ?>. 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") O(\min(n,W)). The expression ( f k map) alters the value x at k, or absence thereof. 8 can be used to insert, delete, or update a value in an . In short :  k ( f k m) = f ( k m). O(\log n). The expression ( f k map) alters the value x at k, or absence thereof.  can be used to inspect, insert, delete, or update a value in an . In short :  k  $  f k m = f ( k m).Example: interactiveAlter :: Int -> IntMap String -> IO (IntMap String) interactiveAlter k m = alterF f k m where f Nothing = do putStrLn $ show k ++ " was not found in the map. Would you like to add it?" getUserResponse1 :: IO (Maybe String) f (Just old) = do putStrLn $ "The key is currently bound to " ++ show old ++ ". Would you like to change or delete it?" getUserResponse2 :: IO (Maybe String)  is the most general operation for working with an individual key that may or may not be in a given map.8The 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")]O(n+m)&. 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 .O(n+m)&. 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 .O(n+m)'. 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"O(n+m). 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  , the element is discarded (proper set difference). If it returns (  y+), the element is updated with a new value y. 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"O(n+m)-. The intersection with a combining function. intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"O(n+m)-. 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"O(n+m):. A high-performance universal combining function. Using , all combining functions can be defined without any loss of efficiency (with exception of ,  and ,, where sharing of some nodes is lost with ).6Please make sure you know what is going on when using , otherwise you can be surprised by unexpected code growth or even corruption of the data structure.When  is given three arguments, it is inlined to the call site. You should therefore use  only to define your custom combining functions. For example, you could define ,  and  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 m2 When calling  combine only1 only2, a function combining two s is created, such thatif 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  and  , but for example  f or  f could be used for any f. O(\log n)&. 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" O(\log n)&. 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" O(\log n)&. 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" O(\log n)&. 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"O(n),. Map a function over all values in the map. map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]O(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")]O(n).  f s ==   $   ((k, v) -> (,) k  $ f k v) ( m)* That is, behaves exactly like a regular   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')]) == Nothing containersO(n)'. Traverse keys/values and collect the   results.O(n). The function  threads an accumulating argument through the map in ascending order of keys. let f a b = (a ++ b, b ++ "X") mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])O(n). The function  threads an accumulating argument through the map in ascending order of keys. 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")]) O(n). The function   threads an accumulating argument through the map in ascending order of keys. Strict in the accumulating argument and the both elements of the result of the function.O(n). The function  threads an accumulating argument through the map in descending order of keys. O(n \log n).  c f s! is the map obtained by applying f to each key of s.)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 .O(n). Map values and collect the   results. let f x = if x == "a" then Just "new a" else Nothing mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"O(n)". Map keys/values and collect the   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"O(n). Map values and separate the   and   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")])O(n)#. Map keys/values and separate the   and   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")])O(n). Build a map from a set 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")] fromSet undefined Data.IntSet.empty == emptyO(n \min(n,W)).. Create a map from a list of key/value pairs. 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")]O(n \min(n,W)). Build a map from a list of key/value pairs with a combining function. See also . 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. Performance!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 slow'because they evaluate as, respectively: fromList [(3, "x" ++ ("x" ++ "xxxxx..xxxxx"))] -- O(n) fromList [(3, ("xxxxx..xxxxx" ++ "x") ++ "x")] -- O(n)5Thus, 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")]7and it is always fast to combine singleton-list values [v] with fromListWith (++), as in: fromListWith (++) $ reverse $ map (\(k, v) -> (k, [v])) someListOfTuplesO(n \min(n,W)). Build a map from a list of key/value pairs with a combining function. See also fromAscListWithKey'. 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 [] == empty!Also see the performance note on .O(n). Build a map from a list of key/value pairs where the keys are in ascending order. fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]O(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. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]!Also see the performance note on .O(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. :The precondition (input list is ascending) is not checked. fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]!Also see the performance note on .O(n). Build a map from a list of key/value pairs where the keys are in ascending order and all distinct. The precondition (input list is strictly ascending) is not checked. fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")] O(n). Build a map from a list of key/value pairs with monotonic keys and a combining function.The precise conditions under which this function works are subtle: For any branch mask, keys with the same prefix w.r.t. the branch mask must occur consecutively in the list.!Also see the performance note on .K(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportable Trustworthy(c) wren romano 2016 BSD-stylelibraries@haskell.orgportable Trustworthy Map covariantly over a  f k x.Map covariantly over a  f k x y.When 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 :: (k -> x -> y -> Maybe z) -> SimpleWhenMatched k x y z When 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  tactic.When 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.When a key is found in both maps, apply a function to the key and values and use the result in the merged map. zipWithMatched :: (k -> x -> y -> z) -> SimpleWhenMatched k x y z Map over the entries whose keys are missing from the other map, optionally removing some. This is the most powerful 0 tactic, but others are usually more efficient. mapMaybeMissing :: (k -> x -> Maybe y) -> SimpleWhenMissing k x y ?mapMaybeMissing f = traverseMaybeMissing (\k x -> pure (f k x))but mapMaybeMissing uses fewer unnecessary   operations.?Map over the entries whose keys are missing from the other map. 7mapMissing :: (k -> x -> y) -> SimpleWhenMissing k x y 5mapMissing f = mapMaybeMissing (\k x -> Just $ f k x)but  mapMissing is somewhat faster.Traverse over the entries whose keys are missing from the other map, optionally producing values to put in the result. This is the most powerful 0 tactic, but others are usually more efficient.Traverse over the entries whose keys are missing from the other map.(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableSafe(c) Daan Leijen 2002 (c) Andriy Palamarchuk 2008 BSD-stylelibraries@haskell.orgportableSafe12=This function is being removed and is no longer usable. Use KG=This function is being removed and is no longer usable. Use KH.=This function is being removed and is no longer usable. Use (.=This function is being removed and is no longer usable. Use . LMNLMNLMNOPQRSTUVWXYZ[\]$^$^$^_$`%a%b%cdefggghi9jklmn;:opqrst2uvwxyz{|}~<()*+ECDnst0m>8*+                                   Y                                                                                          i1jklmn>;:opqrst2GHIu?v*+z{|}~yEF()CD@jklmn;:opqrst2uvwxy{}~<()CDjklmn;:>opqryst2GHIu?vEFz{|}~()CDBCBD  t 2 G H I     ?  v                                                <JCJDt2GHI?v<L)LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL+L.LLLLLL>LLLLLLLLLLL*L-LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL(LLLLLmLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL""%%%LL    L6A containers-0.7-71fcData.Map.Internal!Utils.Containers.Internal.BitUtil"Utils.Containers.Internal.BitQueueData.Sequence.Internal$Utils.Containers.Internal.StrictPairData.Set.InternalData.Set Data.SequenceData.Sequence.Internal.Sorting Data.Tree Data.GraphData.Map.Merge.LazyData.Map.Strict.InternalData.Map.Strict Data.Map.LazyData.Map.Merge.StrictData.Map.Internal.Debug Data.IntSetData.IntSet.InternalData.Containers.ListUtilsData.IntMap.Merge.LazyData.IntMap.InternalData.IntMap.Strict.InternalData.IntMap.LazyData.IntMap.Internal.DebugData.MapData.IntMap.Merge.Strict Data.IntMap#Utils.Containers.Internal.Coercions89!Utils.Containers.Internal.Prelude%Utils.Containers.Internal.PtrEquality4Utils.Containers.Internal.State%Utils.Containers.Internal.StrictMaybe1Preludefoldrfoldltakedrop Data.List takeWhile dropWhile Control.Monad replicateMMapinsert5 Data.FunctiononData.SemigroupOptionfoldMapWithIndexSet notMembermemberfoldnublookupupdateLookupWithKeyIntSet#Utils.Containers.Internal.TypeError$Data.Map.Internal.DeprecatedShowTreeshowTree showTreeWithmergemergeA insertWith insertWithKeyinsertLookupWithKey$Data.IntMap.Internal.DeprecatedDebugData.IntMap.Strict ghc-internal"GHC.Internal.Data.Functor.IdentityIdentity runIdentitybitcounthighestBitMaskshiftRLshiftLLwordSizeBitQueue BitQueueBemptyQBsnocQBbuildQunconsQtoListQ$fShowBitQueueB$fShowBitQueueStaterunState execStateMaybeSNothingSJustS StrictPair:*:toPair IntersectiongetIntersectionSizeBinTip\\nullsizelookupLTlookupGTlookupLElookupGEempty singletondeletealterFisProperSubsetOf isSubsetOfdisjoint lookupMinfindMin lookupMaxfindMax deleteMin deleteMaxunionsunion difference intersection intersectionsfilter partitionmap mapMonotonicfoldr'foldl'elemstoList toAscList toDescListfromList fromAscList fromDescListfromDistinctAscListfromDistinctDescListsplit splitMember findIndex lookupIndexelemAtdeleteAtsplitAttakeWhileAntitonedropWhileAntitone spanAntitonelink deleteFindMin deleteFindMaxminViewmaxViewbin splitRootpowerSetcartesianProduct disjointUnionvalidbalanced $fNFDataSet $fReadSet $fShow1Set $fOrd1Set$fEq1Set $fShowSet$fOrdSet$fEqSet $fIsListSet $fDataSet $fFoldableSet$fSemigroupSet $fMonoidSet$fSemigroupIntersection$fMonoidMergeSet$fSemigroupMergeSet$fShowIntersection$fEqIntersection$fOrdIntersection$fLiftBoxedRepSetViewREmptyR:>ViewLEmptyL:<ElemgetElemNodeNode2Node3DigitOneTwoThreeFour FingerTreeEmptyTSingleDeepSeq MaybeForceSized:|>:<|Empty liftA2Seq intersperse foldDigitfoldNode replicate replicateA cycleTaking<||>><unfoldrunfoldliterateNlengthviewlviewrscanlscanl1scanrscanr1index!?updateadjustadjust'insertAt mapWithIndexfoldWithIndexDigitfoldWithIndexNodetraverseWithIndex fromFunction fromArraychunksOftailsinitsfoldlWithIndexfoldrWithIndex takeWhileL takeWhileR dropWhileL dropWhileRspanlspanrbreaklbreakr elemIndexL elemIndexR elemIndicesL elemIndicesR findIndexL findIndexR findIndicesL findIndicesRreverseunzip unzipWithzipzipWithzip3zipWith3zip4zipWith4$fSizedForceBox$fMaybeForceForceBox $fSizedDigit $fNFDataDigit$fTraversableDigit$fFunctorDigit$fFoldableDigit $fSizedNode $fNFDataNode$fTraversableNode $fFunctorNode$fFoldableNode$fMaybeForceNode$fNFDataFingerTree$fTraversableFingerTree$fFunctorFingerTree$fFoldableFingerTree $fNFDataElem$fTraversableElem$fFoldableElem $fFunctorElem $fSizedElem$fSizedFingerTree$fMaybeForceElem $fMonadZipSeq $fIsStringSeq $fIsListSeq$fSemigroupSeq $fMonoidSeq $fRead1Seq $fReadSeq $fOrd1Seq$fEq1Seq $fShow1Seq $fShowSeq$fOrdSeq$fEqSeq$fAlternativeSeq$fMonadPlusSeq$fApplicativeSeq $fMonadFixSeq $fMonadSeq $fNFDataSeq$fTraversableSeq $fFoldableSeq $fFunctorSeq$fLiftBoxedRepSeq$fTraversableViewL$fFoldableViewL$fFunctorViewL $fDataSeq$fTraversableViewR$fFoldableViewR$fFunctorViewR$fUnzipWithSeq$fUnzipWithFingerTree$fUnzipWithDigit$fUnzipWithNode$fUnzipWithElem $fEqViewR $fOrdViewR $fShowViewR $fReadViewR $fEqViewL $fOrdViewL $fShowViewL $fReadViewL$fLiftBoxedRepViewR$fGenericViewR$fGeneric1TYPEViewR $fDataViewR$fLiftBoxedRepViewL$fGenericViewL$fGeneric1TYPEViewL $fDataViewL $fGenericElem$fGeneric1TYPEElem$fLiftBoxedRepNode $fGenericNode$fGeneric1TYPENode$fLiftBoxedRepDigit$fGenericDigit$fGeneric1TYPEDigit$fLiftBoxedRepFingerTree$fGenericFingerTree$fGeneric1TYPEFingerTreeITQListITQNilITQConsIndexedTaggedQueueITQTQListTQNilTQCons TaggedQueueTQIQListIQNilIQCons IndexedQueueIQQListNilQConsQueueQsortsortBysortOn unstableSortunstableSortByunstableSortOnmergeQmergeTQmergeIQmergeITQpopMinQpopMinIQpopMinTQ popMinITQbuildIQbuildTQbuildITQfoldToMaybeTreefoldToMaybeWithIndexTreeForestTree subForest rootLabeldrawTree drawForestflattenlevelsfoldTree unfoldTree unfoldForest unfoldTreeM unfoldForestMunfoldTreeM_BFunfoldForestM_BF$fMonadZipTree $fNFDataTree$fFoldable1Tree$fFoldableTree$fTraversableTree$fMonadFixTree $fMonadTree$fApplicativeTree $fFunctorTree $fRead1Tree $fShow1Tree $fOrd1Tree $fEq1Tree$fEqTree $fOrdTree $fReadTree $fShowTree $fDataTree $fGenericTree$fGeneric1TYPETree$fLiftBoxedRepTreeEdgeBoundsGraphTableVertexSCC AcyclicSCC NECyclicSCC CyclicSCC flattenSCCs flattenSCCstronglyConnCompstronglyConnCompRverticesedgesbuildG transposeG outdegreeindegreegraphFromEdges'graphFromEdgesdffdfstopSortreverseTopSort componentsscc reachablepathbcc $fFunctorSCC $fNFDataSCC$fTraversableSCC$fFoldable1SCC $fFoldableSCC $fRead1SCC $fShow1SCC$fEq1SCC$fApplicativeSetM $fFunctorSetM $fMonadSetM$fEqSCC $fShowSCC $fReadSCC$fLiftBoxedRepSCC $fGenericSCC$fGeneric1TYPESCC $fDataSCCStackPushNadaFromDistinctMonoStateState0State1SimpleWhenMatched WhenMatched matchedKeySimpleWhenMissing WhenMissing missingKeymissingSubtree AreWeStrictStrictLazy!findWithDefault adjustWithKey updateWithKeyalter atKeyImpl atKeyPlainupdateAt updateMin updateMaxupdateMinWithKeyupdateMaxWithKeyminViewWithKeymaxViewWithKey unionsWith unionWith unionWithKey withoutKeysdifferenceWithdifferenceWithKey restrictKeysintersectionWithintersectionWithKeycomposemapWhenMissingmapGentlyWhenMissingmapGentlyWhenMatchedlmapWhenMissingcontramapFirstWhenMatchedcontramapSecondWhenMatchedrunWhenMatchedrunWhenMissingmapWhenMatchedzipWithMatchedzipWithAMatchedzipWithMaybeMatchedzipWithMaybeAMatched dropMissingpreserveMissingpreserveMissing' mapMissingmapMaybeMissing filterMissingfilterAMissingtraverseMissingtraverseMaybeMissing mergeWithKey isSubmapOf isSubmapOfByisProperSubmapOfisProperSubmapOfBy filterWithKeypartitionWithKeymapMaybemapMaybeWithKeytraverseMaybeWithKey mapEithermapEitherWithKey mapWithKeytraverseWithKeymapAccummapAccumWithKeymapAccumRWithKeymapKeys mapKeysWithmapKeysMonotonic foldrWithKey foldrWithKey' foldlWithKey foldlWithKey'foldMapWithKeykeysassocskeysSetargSetfromSet fromArgSet fromListWithfromListWithKeyfromAscListWithfromDescListWithfromAscListWithKeyfromDescListWithKeyfromDistinctAscList_linkTopfromDistinctAscList_linkAllfromDistinctDescList_linkTopfromDistinctDescList_linkAll foldl'Stack splitLookup insertMaxlink2gluedeltabalancebalanceLbalanceR $fShowMap $fReadMap $fNFDataMap$fBifoldableMap $fFoldableMap$fTraversableMap $fFunctorMap $fRead1Map $fShow1Map $fShow2Map $fOrd1Map $fOrd2Map$fEq1Map$fEq2Map$fOrdMap$fEqMap $fIsListMap $fDataMap$fSemigroupMap $fMonoidMap$fMonadWhenMissing$fApplicativeWhenMissing$fCategoryTYPEWhenMissing$fFunctorWhenMissing$fMonadWhenMatched$fApplicativeWhenMatched$fCategoryTYPEWhenMatched$fFunctorWhenMatched$fLiftBoxedRepMap showsTree showsTreeHangshowWide showsBarsnodewithBar withEmptyordered validsizeKeyBitMapMaskPrefix fromRange suffixBitMask prefixBitMaskbitmapOfzeromatch$fNFDataIntSet $fReadIntSet $fShowIntSet $fOrdIntSet $fEqIntSet $fDataIntSet$fSemigroupIntSet$fMonoidIntSet$fIsListIntSet$fLiftBoxedRepIntSetnubOrdnubOrdOnnubIntnubIntOnIntMapNat natFromInt intFromNat mergeWithKey' linkWithMask binCheckLeft binCheckRightnomatchmaskmaskWshorter branchMask $fRead1IntMap $fReadIntMap $fShow1IntMap $fShowIntMap$fFunctorIntMap $fOrd1IntMap $fOrdIntMap $fEq1IntMap $fEqIntMap$fIsListIntMap $fDataIntMap$fNFDataIntMap$fTraversableIntMap$fFoldableIntMap$fSemigroupIntMap$fMonoidIntMap$fLiftBoxedRepIntMap insertWith'insertWithKey'insertLookupWithKey' foldWithKey.^#GHC.Internal.Data.Foldable.#GHC.Internal.Base$$!++.=<<asTypeOfconstflipid otherwiseuntilGHC.Internal.Data.Eithereitherallandanyconcat concatMapmapM_notElemor sequence_GHC.Internal.Data.Functor<$>GHC.Internal.Data.MaybemaybeGHC.Internal.Data.OldListlinesunlinesunwordswordsGHC.Internal.Data.TuplecurryfstsnduncurryGHC.Internal.ErrerrorerrorWithoutStackTrace undefinedGHC.Internal.IO.ExceptionioError userErrorGHC.Internal.List!!breakcycleheadinititeratelastrepeatspantailunzip3GHC.Internal.NumsubtractGHC.Internal.Readlex readParenGHC.Internal.Real^^^even fromIntegralgcdlcmodd realToFracGHC.Internal.ShowshowChar showParen showStringshowsGHC.Internal.System.IO appendFilegetChar getContentsgetLineinteractprintputCharputStrputStrLnreadFilereadIOreadLn writeFileGHC.Internal.Text.Readreadreadsghc-prim GHC.Classes&&not||GHC.Primseq Applicative*><*<*>liftA2pureFunctor<$fmapMonad>>>>=returnMonoidmappendmconcatmempty Semigroup<>GHC.Internal.Control.Monad.Fail MonadFailfailEitherLeftRightFoldableelemfoldMapfoldl1foldr1maximumminimumproductsumGHC.Internal.Data.Traversable TraversablemapMsequence sequenceAtraverseGHC.Internal.EnumBoundedmaxBoundminBoundEnumenumFrom enumFromThenenumFromThenTo enumFromTofromEnumpredsucctoEnumGHC.Internal.FloatFloating**acosacoshasinasinhatanatanhcoscoshexploglogBasepisinsinhsqrttantanh RealFloatatan2 decodeFloat encodeFloatexponent floatDigits floatRadix floatRangeisDenormalizedisIEEE isInfiniteisNaNisNegativeZero scaleFloat significandGHC.Internal.IOFilePathIOErrorNum*+-abs fromIntegernegatesignumReadreadList readsPrec Fractional/ fromRationalrecipIntegraldivdivModmodquotquotRemrem toIntegerRationalReal toRationalRealFracceilingfloorproperFractionroundtruncateShowshowshowList showsPrecShowS)GHC.Internal.Text.ParserCombinators.ReadPReadSEq/===Ord<<=>>=comparemaxmin GHC.TypesIOOrderingEQGTLT ghc-bignumGHC.Num.IntegerIntegerStringGHC.Internal.MaybeMaybeJustNothingBoolFalseTrueCharDoubleFloatIntWord~ptrEqhetPtrEqmaybeStoMaybetoMaybeSDeletedInsertedDigit23RigidThincoerceFT liftA2MiddlemapMulFTrigidify rigidifyRightthin digitToTree'applicativeTree replicateEachGHC.Internal.ArrArrayuncheckedSplitAt tailsTree initsTree fmapReversesplitMapzipWith' fromList2baseControl.Monad.ZipmzipWithmunzip Rep_ViewR Rep1_ViewR Rep_ViewL Rep1_ViewLRep_Elem Rep1_ElemRep_Node Rep1_Node Rep_Digit Rep1_DigitRep_FingerTreeRep1_FingerTreeRep_Tree Rep1_TreeRep_SCCRep1_SCCfind insertWithRinsertWithKeyRGHC.Internal.Data.Functor.ConstConstboolfilterWithKeyA mapAccumLArg fromMonoList lookupPrefixfromMonoListWithKeyWhoopsSymbol