Merge pull request #239 from treeowl/map-strict-trav
[packages/containers.git] / Data / Map / Strict.hs
1 {-# LANGUAGE CPP #-}
2 {-# LANGUAGE BangPatterns #-}
3 #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
4 {-# LANGUAGE Trustworthy #-}
5 #endif
6
7 #include "containers.h"
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module : Data.Map.Strict
12 -- Copyright : (c) Daan Leijen 2002
13 -- (c) Andriy Palamarchuk 2008
14 -- License : BSD-style
15 -- Maintainer : libraries@haskell.org
16 -- Stability : provisional
17 -- Portability : portable
18 --
19 -- An efficient implementation of ordered maps from keys to values
20 -- (dictionaries).
21 --
22 -- API of this module is strict in both the keys and the values.
23 -- If you need value-lazy maps, use "Data.Map.Lazy" instead.
24 -- The 'Map' type is shared between the lazy and strict modules,
25 -- meaning that the same 'Map' value can be passed to functions in
26 -- both modules (although that is rarely needed).
27 --
28 -- These modules are intended to be imported qualified, to avoid name
29 -- clashes with Prelude functions, e.g.
30 --
31 -- > import qualified Data.Map.Strict as Map
32 --
33 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
34 -- trees of /bounded balance/) as described by:
35 --
36 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
37 -- Journal of Functional Programming 3(4):553-562, October 1993,
38 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
39 --
40 -- * J. Nievergelt and E.M. Reingold,
41 -- \"/Binary search trees of bounded balance/\",
42 -- SIAM journal of computing 2(1), March 1973.
43 --
44 -- Note that the implementation is /left-biased/ -- the elements of a
45 -- first argument are always preferred to the second, for example in
46 -- 'union' or 'insert'.
47 --
48 -- /Warning/: The size of the map must not exceed @maxBound::Int@. Violation of
49 -- this condition is not detected and if the size limit is exceeded, its
50 -- behaviour is undefined.
51 --
52 -- Operation comments contain the operation time complexity in
53 -- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>).
54 --
55 -- Be aware that the 'Functor', 'Traversable' and 'Data' instances
56 -- are the same as for the "Data.Map.Lazy" module, so if they are used
57 -- on strict maps, the resulting maps will be lazy.
58 -----------------------------------------------------------------------------
59
60 -- See the notes at the beginning of Data.Map.Base.
61
62 module Data.Map.Strict
63 (
64 -- * Strictness properties
65 -- $strictness
66
67 -- * Map type
68 #if !defined(TESTING)
69 Map -- instance Eq,Show,Read
70 #else
71 Map(..) -- instance Eq,Show,Read
72 #endif
73
74 -- * Operators
75 , (!), (\\)
76
77 -- * Query
78 , null
79 , size
80 , member
81 , notMember
82 , lookup
83 , findWithDefault
84 , lookupLT
85 , lookupGT
86 , lookupLE
87 , lookupGE
88
89 -- * Construction
90 , empty
91 , singleton
92
93 -- ** Insertion
94 , insert
95 , insertWith
96 , insertWithKey
97 , insertLookupWithKey
98
99 -- ** Delete\/Update
100 , delete
101 , adjust
102 , adjustWithKey
103 , update
104 , updateWithKey
105 , updateLookupWithKey
106 , alter
107 , alterF
108
109 -- * Combine
110
111 -- ** Union
112 , union
113 , unionWith
114 , unionWithKey
115 , unions
116 , unionsWith
117
118 -- ** Difference
119 , difference
120 , differenceWith
121 , differenceWithKey
122
123 -- ** Intersection
124 , intersection
125 , intersectionWith
126 , intersectionWithKey
127
128 -- ** Universal combining function
129 , mergeWithKey
130
131 -- * Traversal
132 -- ** Map
133 , map
134 , mapWithKey
135 , traverseWithKey
136 , mapAccum
137 , mapAccumWithKey
138 , mapAccumRWithKey
139 , mapKeys
140 , mapKeysWith
141 , mapKeysMonotonic
142
143 -- * Folds
144 , foldr
145 , foldl
146 , foldrWithKey
147 , foldlWithKey
148 , foldMapWithKey
149
150 -- ** Strict folds
151 , foldr'
152 , foldl'
153 , foldrWithKey'
154 , foldlWithKey'
155
156 -- * Conversion
157 , elems
158 , keys
159 , assocs
160 , keysSet
161 , fromSet
162
163 -- ** Lists
164 , toList
165 , fromList
166 , fromListWith
167 , fromListWithKey
168
169 -- ** Ordered lists
170 , toAscList
171 , toDescList
172 , fromAscList
173 , fromAscListWith
174 , fromAscListWithKey
175 , fromDistinctAscList
176
177 -- * Filter
178 , filter
179 , filterWithKey
180 , partition
181 , partitionWithKey
182
183 , mapMaybe
184 , mapMaybeWithKey
185 , mapEither
186 , mapEitherWithKey
187
188 , split
189 , splitLookup
190 , splitRoot
191
192 -- * Submap
193 , isSubmapOf, isSubmapOfBy
194 , isProperSubmapOf, isProperSubmapOfBy
195
196 -- * Indexed
197 , lookupIndex
198 , findIndex
199 , elemAt
200 , updateAt
201 , deleteAt
202
203 -- * Min\/Max
204 , findMin
205 , findMax
206 , deleteMin
207 , deleteMax
208 , deleteFindMin
209 , deleteFindMax
210 , updateMin
211 , updateMax
212 , updateMinWithKey
213 , updateMaxWithKey
214 , minView
215 , maxView
216 , minViewWithKey
217 , maxViewWithKey
218
219 -- * Debugging
220 , showTree
221 , showTreeWith
222 , valid
223
224 #if defined(TESTING)
225 -- * Internals
226 , bin
227 , balanced
228 , link
229 , merge
230 #endif
231 ) where
232
233 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
234
235 import Data.Map.Base hiding
236 ( findWithDefault
237 , singleton
238 , insert
239 , insertWith
240 , insertWithKey
241 , insertLookupWithKey
242 , adjust
243 , adjustWithKey
244 , update
245 , updateWithKey
246 , updateLookupWithKey
247 , alter
248 , alterF
249 , unionWith
250 , unionWithKey
251 , unionsWith
252 , differenceWith
253 , differenceWithKey
254 , intersectionWith
255 , intersectionWithKey
256 , mergeWithKey
257 , map
258 , mapWithKey
259 , mapAccum
260 , mapAccumWithKey
261 , mapAccumRWithKey
262 , mapKeysWith
263 , fromSet
264 , fromList
265 , fromListWith
266 , fromListWithKey
267 , fromAscList
268 , fromAscListWith
269 , fromAscListWithKey
270 , fromDistinctAscList
271 , mapMaybe
272 , mapMaybeWithKey
273 , mapEither
274 , mapEitherWithKey
275 , traverseWithKey
276 , updateAt
277 , updateMin
278 , updateMax
279 , updateMinWithKey
280 , updateMaxWithKey
281 )
282 import Control.Applicative (Const (..))
283 #if !MIN_VERSION_base(4,8,0)
284 import Control.Applicative (Applicative (..), (<$>))
285 #endif
286 import qualified Data.Set.Base as Set
287 import Data.Utils.StrictFold
288 import Data.Utils.StrictPair
289
290 import Data.Bits (shiftL, shiftR)
291 #if __GLASGOW_HASKELL__ >= 709
292 import Data.Coerce
293 #endif
294
295 #if __GLASGOW_HASKELL__ && MIN_VERSION_base(4,8,0)
296 import Data.Functor.Identity (Identity (..))
297 #endif
298
299
300 -- $strictness
301 --
302 -- This module satisfies the following strictness properties:
303 --
304 -- 1. Key arguments are evaluated to WHNF;
305 --
306 -- 2. Keys and values are evaluated to WHNF before they are stored in
307 -- the map.
308 --
309 -- Here's an example illustrating the first property:
310 --
311 -- > delete undefined m == undefined
312 --
313 -- Here are some examples that illustrate the second property:
314 --
315 -- > map (\ v -> undefined) m == undefined -- m is not empty
316 -- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
317
318 {--------------------------------------------------------------------
319 Query
320 --------------------------------------------------------------------}
321
322 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
323 -- the value at key @k@ or returns default value @def@
324 -- when the key is not in the map.
325 --
326 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
327 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
328
329 -- See Map.Base.Note: Local 'go' functions and capturing
330 findWithDefault :: Ord k => a -> k -> Map k a -> a
331 findWithDefault def k = k `seq` go
332 where
333 go Tip = def
334 go (Bin _ kx x l r) = case compare k kx of
335 LT -> go l
336 GT -> go r
337 EQ -> x
338 #if __GLASGOW_HASKELL__
339 {-# INLINABLE findWithDefault #-}
340 #else
341 {-# INLINE findWithDefault #-}
342 #endif
343
344 {--------------------------------------------------------------------
345 Construction
346 --------------------------------------------------------------------}
347
348 -- | /O(1)/. A map with a single element.
349 --
350 -- > singleton 1 'a' == fromList [(1, 'a')]
351 -- > size (singleton 1 'a') == 1
352
353 singleton :: k -> a -> Map k a
354 singleton k x = x `seq` Bin 1 k x Tip Tip
355 {-# INLINE singleton #-}
356
357 {--------------------------------------------------------------------
358 Insertion
359 --------------------------------------------------------------------}
360 -- | /O(log n)/. Insert a new key and value in the map.
361 -- If the key is already present in the map, the associated value is
362 -- replaced with the supplied value. 'insert' is equivalent to
363 -- @'insertWith' 'const'@.
364 --
365 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
366 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
367 -- > insert 5 'x' empty == singleton 5 'x'
368
369 -- See Map.Base.Note: Type of local 'go' function
370 insert :: Ord k => k -> a -> Map k a -> Map k a
371 insert = go
372 where
373 go :: Ord k => k -> a -> Map k a -> Map k a
374 go !kx !x Tip = singleton kx x
375 go kx x (Bin sz ky y l r) =
376 case compare kx ky of
377 LT -> balanceL ky y (go kx x l) r
378 GT -> balanceR ky y l (go kx x r)
379 EQ -> Bin sz kx x l r
380 #if __GLASGOW_HASKELL__
381 {-# INLINABLE insert #-}
382 #else
383 {-# INLINE insert #-}
384 #endif
385
386 -- | /O(log n)/. Insert with a function, combining new value and old value.
387 -- @'insertWith' f key value mp@
388 -- will insert the pair (key, value) into @mp@ if key does
389 -- not exist in the map. If the key does exist, the function will
390 -- insert the pair @(key, f new_value old_value)@.
391 --
392 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
393 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
394 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
395
396 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
397 insertWith f = insertWithKey (\_ x' y' -> f x' y')
398 #if __GLASGOW_HASKELL__
399 {-# INLINABLE insertWith #-}
400 #else
401 {-# INLINE insertWith #-}
402 #endif
403
404 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
405 -- @'insertWithKey' f key value mp@
406 -- will insert the pair (key, value) into @mp@ if key does
407 -- not exist in the map. If the key does exist, the function will
408 -- insert the pair @(key,f key new_value old_value)@.
409 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
410 --
411 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
412 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
413 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
414 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
415
416 -- See Map.Base.Note: Type of local 'go' function
417 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
418 insertWithKey = go
419 where
420 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
421 -- Forcing `kx` may look redundant, but it's possible `compare` will
422 -- be lazy.
423 go _ !kx x Tip = singleton kx x
424 go f kx x (Bin sy ky y l r) =
425 case compare kx ky of
426 LT -> balanceL ky y (go f kx x l) r
427 GT -> balanceR ky y l (go f kx x r)
428 EQ -> let !x' = f kx x y
429 in Bin sy kx x' l r
430 #if __GLASGOW_HASKELL__
431 {-# INLINABLE insertWithKey #-}
432 #else
433 {-# INLINE insertWithKey #-}
434 #endif
435
436 -- | /O(log n)/. Combines insert operation with old value retrieval.
437 -- The expression (@'insertLookupWithKey' f k x map@)
438 -- is a pair where the first element is equal to (@'lookup' k map@)
439 -- and the second element equal to (@'insertWithKey' f k x map@).
440 --
441 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
442 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
443 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
444 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
445 --
446 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
447 --
448 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
449 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
450 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
451
452 -- See Map.Base.Note: Type of local 'go' function
453 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
454 -> (Maybe a, Map k a)
455 insertLookupWithKey f0 kx0 x0 t0 = toPair $ go f0 kx0 x0 t0
456 where
457 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> StrictPair (Maybe a) (Map k a)
458 go _ !kx x Tip = Nothing :*: singleton kx x
459 go f kx x (Bin sy ky y l r) =
460 case compare kx ky of
461 LT -> let (found :*: l') = go f kx x l
462 in found :*: balanceL ky y l' r
463 GT -> let (found :*: r') = go f kx x r
464 in found :*: balanceR ky y l r'
465 EQ -> let x' = f kx x y
466 in x' `seq` (Just y :*: Bin sy kx x' l r)
467 #if __GLASGOW_HASKELL__
468 {-# INLINABLE insertLookupWithKey #-}
469 #else
470 {-# INLINE insertLookupWithKey #-}
471 #endif
472
473 {--------------------------------------------------------------------
474 Deletion
475 --------------------------------------------------------------------}
476
477 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
478 -- When the key is not
479 -- a member of the map, the original map is returned.
480 --
481 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
482 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
483 -- > adjust ("new " ++) 7 empty == empty
484
485 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
486 adjust f = adjustWithKey (\_ x -> f x)
487 #if __GLASGOW_HASKELL__
488 {-# INLINABLE adjust #-}
489 #else
490 {-# INLINE adjust #-}
491 #endif
492
493 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
494 -- a member of the map, the original map is returned.
495 --
496 -- > let f key x = (show key) ++ ":new " ++ x
497 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
498 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
499 -- > adjustWithKey f 7 empty == empty
500
501 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
502 adjustWithKey = go
503 where
504 go :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
505 go _ !_ Tip = Tip
506 go f k (Bin sx kx x l r) =
507 case compare k kx of
508 LT -> Bin sx kx x (go f k l) r
509 GT -> Bin sx kx x l (go f k r)
510 EQ -> Bin sx kx x' l r
511 where !x' = f kx x
512 #if __GLASGOW_HASKELL__
513 {-# INLINABLE adjustWithKey #-}
514 #else
515 {-# INLINE adjustWithKey #-}
516 #endif
517
518 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
519 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
520 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
521 --
522 -- > let f x = if x == "a" then Just "new a" else Nothing
523 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
524 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
525 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
526
527 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
528 update f = updateWithKey (\_ x -> f x)
529 #if __GLASGOW_HASKELL__
530 {-# INLINABLE update #-}
531 #else
532 {-# INLINE update #-}
533 #endif
534
535 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
536 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
537 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
538 -- to the new value @y@.
539 --
540 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
541 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
542 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
543 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
544
545 -- See Map.Base.Note: Type of local 'go' function
546 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
547 updateWithKey = go
548 where
549 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
550 go _ !_ Tip = Tip
551 go f k(Bin sx kx x l r) =
552 case compare k kx of
553 LT -> balanceR kx x (go f k l) r
554 GT -> balanceL kx x l (go f k r)
555 EQ -> case f kx x of
556 Just x' -> x' `seq` Bin sx kx x' l r
557 Nothing -> glue l r
558 #if __GLASGOW_HASKELL__
559 {-# INLINABLE updateWithKey #-}
560 #else
561 {-# INLINE updateWithKey #-}
562 #endif
563
564 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
565 -- The function returns changed value, if it is updated.
566 -- Returns the original key value if the map entry is deleted.
567 --
568 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
569 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
570 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
571 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
572
573 -- See Map.Base.Note: Type of local 'go' function
574 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
575 updateLookupWithKey f0 k0 t0 = toPair $ go f0 k0 t0
576 where
577 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> StrictPair (Maybe a) (Map k a)
578 go _ !_ Tip = (Nothing :*: Tip)
579 go f k (Bin sx kx x l r) =
580 case compare k kx of
581 LT -> let (found :*: l') = go f k l
582 in found :*: balanceR kx x l' r
583 GT -> let (found :*: r') = go f k r
584 in found :*: balanceL kx x l r'
585 EQ -> case f kx x of
586 Just x' -> x' `seq` (Just x' :*: Bin sx kx x' l r)
587 Nothing -> (Just x :*: glue l r)
588 #if __GLASGOW_HASKELL__
589 {-# INLINABLE updateLookupWithKey #-}
590 #else
591 {-# INLINE updateLookupWithKey #-}
592 #endif
593
594 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
595 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
596 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
597 --
598 -- > let f _ = Nothing
599 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
600 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
601 -- >
602 -- > let f _ = Just "c"
603 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
604 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
605
606 -- See Map.Base.Note: Type of local 'go' function
607 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
608 alter = go
609 where
610 go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
611 go f !k Tip = case f Nothing of
612 Nothing -> Tip
613 Just x -> singleton k x
614
615 go f k (Bin sx kx x l r) = case compare k kx of
616 LT -> balance kx x (go f k l) r
617 GT -> balance kx x l (go f k r)
618 EQ -> case f (Just x) of
619 Just x' -> x' `seq` Bin sx kx x' l r
620 Nothing -> glue l r
621 #if __GLASGOW_HASKELL__
622 {-# INLINABLE alter #-}
623 #else
624 {-# INLINE alter #-}
625 #endif
626
627 -- | /O(log n)/. The expression (@'alterF' f k map@) alters the value @x@ at @k@, or absence thereof.
628 -- 'alterF' can be used to inspect, insert, delete, or update a value in a 'Map'.
629 -- In short : @'lookup' k <$> 'alterF' f k m = f ('lookup' k m)@.
630 --
631 -- Example:
632 -- @
633 -- interactiveAlter :: Int -> Map Int String -> IO (Map Int String)
634 -- interactiveAlter k m = alterF f k m where
635 -- f Nothing -> do
636 -- putStrLn $ show k ++
637 -- " was not found in the map. Would you like to add it?"
638 -- getUserResponse1 :: IO (Maybe String)
639 -- f (Just old) -> do
640 -- putStrLn "The key is currently bound to " ++ show old ++
641 -- ". Would you like to change or delete it?"
642 -- getUserresponse2 :: IO (Maybe String)
643 -- @
644 --
645 -- 'alterF' is the most general operation for working with an individual
646 -- key that may or may not be in a given map. When used with trivial
647 -- functors like 'Identity' and 'Const', it is often slightly slower than
648 -- more specialized combinators like 'lookup' and 'insert'. However, when
649 -- the functor is non-trivial and key comparison is not particularly cheap,
650 -- it is the fastest way.
651 --
652 -- Note on rewrite rules:
653 --
654 -- This module includes GHC rewrite rules to optimize 'alterF' for
655 -- the 'Const' and 'Identity' functors. In general, these rules
656 -- improve performance. The sole exception is that when using
657 -- 'Identity', deleting a key that is already absent takes longer
658 -- than it would without the rules. If you expect this to occur
659 -- a very large fraction of the time, you might consider using a
660 -- private copy of the 'Identity' type.
661 --
662 -- Note: 'alterF' is a flipped version of the 'at' combinator from
663 -- 'Control.Lens.At'.
664 alterF :: (Functor f, Ord k)
665 => (Maybe a -> f (Maybe a)) -> k -> Map k a -> f (Map k a)
666 alterF f k m = atKeyImpl Strict k f m
667
668 #ifndef __GLASGOW_HASKELL__
669 {-# INLINE alterF #-}
670 #else
671 {-# INLINABLE [2] alterF #-}
672
673 -- We can save a little time by recognizing the special case of
674 -- `Control.Applicative.Const` and just doing a lookup.
675 {-# RULES
676 "alterF/Const" forall k (f :: Maybe a -> Const b (Maybe a)) . alterF f k = \m -> Const . getConst . f $ lookup k m
677 #-}
678 #if MIN_VERSION_base(4,8,0)
679 -- base 4.8 and above include Data.Functor.Identity, so we can
680 -- save a pretty decent amount of time by handling it specially.
681 {-# RULES
682 "alterF/Identity" forall k f . alterF f k = atKeyIdentity k f
683 #-}
684
685 atKeyIdentity :: Ord k => k -> (Maybe a -> Identity (Maybe a)) -> Map k a -> Identity (Map k a)
686 atKeyIdentity k f t = Identity $ atKeyPlain Strict k (coerce f) t
687 {-# INLINABLE atKeyIdentity #-}
688 #endif
689 #endif
690
691 {--------------------------------------------------------------------
692 Indexing
693 --------------------------------------------------------------------}
694
695 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
696 -- invalid index is used.
697 --
698 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
699 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
700 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
701 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
702 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
703 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
704 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
705 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
706
707 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
708 updateAt f i t = i `seq`
709 case t of
710 Tip -> error "Map.updateAt: index out of range"
711 Bin sx kx x l r -> case compare i sizeL of
712 LT -> balanceR kx x (updateAt f i l) r
713 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
714 EQ -> case f kx x of
715 Just x' -> x' `seq` Bin sx kx x' l r
716 Nothing -> glue l r
717 where
718 sizeL = size l
719
720 {--------------------------------------------------------------------
721 Minimal, Maximal
722 --------------------------------------------------------------------}
723
724 -- | /O(log n)/. Update the value at the minimal key.
725 --
726 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
727 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
728
729 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
730 updateMin f m
731 = updateMinWithKey (\_ x -> f x) m
732
733 -- | /O(log n)/. Update the value at the maximal key.
734 --
735 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
736 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
737
738 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
739 updateMax f m
740 = updateMaxWithKey (\_ x -> f x) m
741
742
743 -- | /O(log n)/. Update the value at the minimal key.
744 --
745 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
746 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
747
748 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
749 updateMinWithKey _ Tip = Tip
750 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
751 Nothing -> r
752 Just x' -> x' `seq` Bin sx kx x' Tip r
753 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
754
755 -- | /O(log n)/. Update the value at the maximal key.
756 --
757 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
758 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
759
760 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
761 updateMaxWithKey _ Tip = Tip
762 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
763 Nothing -> l
764 Just x' -> x' `seq` Bin sx kx x' l Tip
765 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
766
767 {--------------------------------------------------------------------
768 Union.
769 --------------------------------------------------------------------}
770
771 -- | The union of a list of maps, with a combining operation:
772 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
773 --
774 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
775 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
776
777 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
778 unionsWith f ts
779 = foldlStrict (unionWith f) empty ts
780 #if __GLASGOW_HASKELL__
781 {-# INLINABLE unionsWith #-}
782 #endif
783
784 {--------------------------------------------------------------------
785 Union with a combining function
786 --------------------------------------------------------------------}
787 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
788 --
789 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
790
791 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
792 unionWith f m1 m2
793 = unionWithKey (\_ x y -> f x y) m1 m2
794 #if __GLASGOW_HASKELL__
795 {-# INLINABLE unionWith #-}
796 #endif
797
798 -- | /O(n+m)/.
799 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
800 --
801 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
802 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
803
804 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
805 unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
806 #if __GLASGOW_HASKELL__
807 {-# INLINABLE unionWithKey #-}
808 #endif
809
810 {--------------------------------------------------------------------
811 Difference
812 --------------------------------------------------------------------}
813
814 -- | /O(n+m)/. Difference with a combining function.
815 -- When two equal keys are
816 -- encountered, the combining function is applied to the values of these keys.
817 -- If it returns 'Nothing', the element is discarded (proper set difference). If
818 -- it returns (@'Just' y@), the element is updated with a new value @y@.
819 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
820 --
821 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
822 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
823 -- > == singleton 3 "b:B"
824
825 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
826 differenceWith f m1 m2
827 = differenceWithKey (\_ x y -> f x y) m1 m2
828 #if __GLASGOW_HASKELL__
829 {-# INLINABLE differenceWith #-}
830 #endif
831
832 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
833 -- encountered, the combining function is applied to the key and both values.
834 -- If it returns 'Nothing', the element is discarded (proper set difference). If
835 -- it returns (@'Just' y@), the element is updated with a new value @y@.
836 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
837 --
838 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
839 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
840 -- > == singleton 3 "3:b|B"
841
842 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
843 differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
844 #if __GLASGOW_HASKELL__
845 {-# INLINABLE differenceWithKey #-}
846 #endif
847
848
849 {--------------------------------------------------------------------
850 Intersection
851 --------------------------------------------------------------------}
852
853 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
854 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
855 --
856 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
857
858 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
859 intersectionWith f m1 m2
860 = intersectionWithKey (\_ x y -> f x y) m1 m2
861 #if __GLASGOW_HASKELL__
862 {-# INLINABLE intersectionWith #-}
863 #endif
864
865 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
866 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
867 --
868 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
869 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
870
871
872 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
873 intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
874 #if __GLASGOW_HASKELL__
875 {-# INLINABLE intersectionWithKey #-}
876 #endif
877
878
879 {--------------------------------------------------------------------
880 MergeWithKey
881 --------------------------------------------------------------------}
882
883 -- | /O(n+m)/. A high-performance universal combining function. This function
884 -- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
885 -- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
886 -- used to define other custom combine functions.
887 --
888 -- Please make sure you know what is going on when using 'mergeWithKey',
889 -- otherwise you can be surprised by unexpected code growth or even
890 -- corruption of the data structure.
891 --
892 -- When 'mergeWithKey' is given three arguments, it is inlined to the call
893 -- site. You should therefore use 'mergeWithKey' only to define your custom
894 -- combining functions. For example, you could define 'unionWithKey',
895 -- 'differenceWithKey' and 'intersectionWithKey' as
896 --
897 -- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
898 -- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
899 -- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
900 --
901 -- When calling @'mergeWithKey' combine only1 only2@, a function combining two
902 -- 'Map's is created, such that
903 --
904 -- * if a key is present in both maps, it is passed with both corresponding
905 -- values to the @combine@ function. Depending on the result, the key is either
906 -- present in the result with specified value, or is left out;
907 --
908 -- * a nonempty subtree present only in the first map is passed to @only1@ and
909 -- the output is added to the result;
910 --
911 -- * a nonempty subtree present only in the second map is passed to @only2@ and
912 -- the output is added to the result.
913 --
914 -- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
915 -- The values can be modified arbitrarily. Most common variants of @only1@ and
916 -- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
917 -- @'filterWithKey' f@ could be used for any @f@.
918
919 mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
920 -> Map k a -> Map k b -> Map k c
921 mergeWithKey f g1 g2 = go
922 where
923 go Tip t2 = g2 t2
924 go t1 Tip = g1 t1
925 go t1 t2 = hedgeMerge NothingS NothingS t1 t2
926
927 hedgeMerge _ _ t1 Tip = g1 t1
928 hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r)
929 hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
930 (found, trim_t2) = trimLookupLo kx bhi t2
931 r' = hedgeMerge bmi bhi r trim_t2
932 in case found of
933 Nothing -> case g1 (singleton kx x) of
934 Tip -> merge l' r'
935 (Bin _ _ x' Tip Tip) -> link kx x' l' r'
936 _ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
937 Just x2 -> case f kx x x2 of
938 Nothing -> merge l' r'
939 Just x' -> x' `seq` link kx x' l' r'
940 where bmi = JustS kx
941 {-# INLINE mergeWithKey #-}
942
943 {--------------------------------------------------------------------
944 Filter and partition
945 --------------------------------------------------------------------}
946
947 -- | /O(n)/. Map values and collect the 'Just' results.
948 --
949 -- > let f x = if x == "a" then Just "new a" else Nothing
950 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
951
952 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
953 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
954
955 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
956 --
957 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
958 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
959
960 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
961 mapMaybeWithKey _ Tip = Tip
962 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
963 Just y -> y `seq` link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
964 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
965
966 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
967 --
968 -- > let f a = if a < "c" then Left a else Right a
969 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
970 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
971 -- >
972 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
973 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
974
975 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
976 mapEither f m
977 = mapEitherWithKey (\_ x -> f x) m
978
979 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
980 --
981 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
982 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
983 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
984 -- >
985 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
986 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
987
988 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
989 mapEitherWithKey f0 t0 = toPair $ go f0 t0
990 where
991 go _ Tip = (Tip :*: Tip)
992 go f (Bin _ kx x l r) = case f kx x of
993 Left y -> y `seq` (link kx y l1 r1 :*: merge l2 r2)
994 Right z -> z `seq` (merge l1 r1 :*: link kx z l2 r2)
995 where
996 (l1 :*: l2) = go f l
997 (r1 :*: r2) = go f r
998
999 {--------------------------------------------------------------------
1000 Mapping
1001 --------------------------------------------------------------------}
1002 -- | /O(n)/. Map a function over all values in the map.
1003 --
1004 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
1005
1006 map :: (a -> b) -> Map k a -> Map k b
1007 map _ Tip = Tip
1008 map f (Bin sx kx x l r) = let x' = f x in x' `seq` Bin sx kx x' (map f l) (map f r)
1009 #ifdef __GLASGOW_HASKELL__
1010 {-# NOINLINE [1] map #-}
1011 {-# RULES
1012 "map/map" forall f g xs . map f (map g xs) = map (f . g) xs
1013 #-}
1014 #endif
1015 #if __GLASGOW_HASKELL__ >= 709
1016 -- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
1017 {-# RULES
1018 "mapSeq/coerce" map coerce = coerce
1019 #-}
1020 #endif
1021
1022 -- | /O(n)/. Map a function over all values in the map.
1023 --
1024 -- > let f key x = (show key) ++ ":" ++ x
1025 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
1026
1027 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
1028 mapWithKey _ Tip = Tip
1029 mapWithKey f (Bin sx kx x l r) =
1030 let x' = f kx x
1031 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
1032
1033 #ifdef __GLASGOW_HASKELL__
1034 {-# NOINLINE [1] mapWithKey #-}
1035 {-# RULES
1036 "mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
1037 mapWithKey (\k a -> f k (g k a)) xs
1038 "mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
1039 mapWithKey (\k a -> f k (g a)) xs
1040 "map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
1041 mapWithKey (\k a -> f (g k a)) xs
1042 #-}
1043 #endif
1044
1045 -- | /O(n)/.
1046 -- @'traverseWithKey' f m == 'fromList' <$> 'traverse' (\(k, v) -> (\v' -> v' `seq` (k,v')) <$> f k v) ('toList' m)@
1047 -- That is, it behaves much like a regular 'traverse' except that the traversing
1048 -- function also has access to the key associated with a value and the values are
1049 -- forced before they are installed in the result map.
1050 --
1051 -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')])
1052 -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == Nothing
1053 traverseWithKey :: Applicative t => (k -> a -> t b) -> Map k a -> t (Map k b)
1054 traverseWithKey f = go
1055 where
1056 go Tip = pure Tip
1057 go (Bin 1 k v _ _) = (\ !v' -> Bin 1 k v' Tip Tip) <$> f k v
1058 go (Bin s k v l r) = (\ l' !v' r' -> Bin s k v' l' r') <$> go l <*> f k v <*> go r
1059 {-# INLINE traverseWithKey #-}
1060
1061 -- | /O(n)/. The function 'mapAccum' threads an accumulating
1062 -- argument through the map in ascending order of keys.
1063 --
1064 -- > let f a b = (a ++ b, b ++ "X")
1065 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
1066
1067 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1068 mapAccum f a m
1069 = mapAccumWithKey (\a' _ x' -> f a' x') a m
1070
1071 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
1072 -- argument through the map in ascending order of keys.
1073 --
1074 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
1075 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
1076
1077 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1078 mapAccumWithKey f a t
1079 = mapAccumL f a t
1080
1081 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
1082 -- argument through the map in ascending order of keys.
1083 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1084 mapAccumL _ a Tip = (a,Tip)
1085 mapAccumL f a (Bin sx kx x l r) =
1086 let (a1,l') = mapAccumL f a l
1087 (a2,x') = f a1 kx x
1088 (a3,r') = mapAccumL f a2 r
1089 in x' `seq` (a3,Bin sx kx x' l' r')
1090
1091 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
1092 -- argument through the map in descending order of keys.
1093 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1094 mapAccumRWithKey _ a Tip = (a,Tip)
1095 mapAccumRWithKey f a (Bin sx kx x l r) =
1096 let (a1,r') = mapAccumRWithKey f a r
1097 (a2,x') = f a1 kx x
1098 (a3,l') = mapAccumRWithKey f a2 l
1099 in x' `seq` (a3,Bin sx kx x' l' r')
1100
1101 -- | /O(n*log n)/.
1102 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1103 --
1104 -- The size of the result may be smaller if @f@ maps two or more distinct
1105 -- keys to the same new key. In this case the associated values will be
1106 -- combined using @c@.
1107 --
1108 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1109 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1110
1111 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1112 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
1113 #if __GLASGOW_HASKELL__
1114 {-# INLINABLE mapKeysWith #-}
1115 #endif
1116
1117 {--------------------------------------------------------------------
1118 Conversions
1119 --------------------------------------------------------------------}
1120
1121 -- | /O(n)/. Build a map from a set of keys and a function which for each key
1122 -- computes its value.
1123 --
1124 -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
1125 -- > fromSet undefined Data.Set.empty == empty
1126
1127 fromSet :: (k -> a) -> Set.Set k -> Map k a
1128 fromSet _ Set.Tip = Tip
1129 fromSet f (Set.Bin sz x l r) = case f x of v -> v `seq` Bin sz x v (fromSet f l) (fromSet f r)
1130
1131 {--------------------------------------------------------------------
1132 Lists
1133 use [foldlStrict] to reduce demand on the control-stack
1134 --------------------------------------------------------------------}
1135 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1136 -- If the list contains more than one value for the same key, the last value
1137 -- for the key is retained.
1138 --
1139 -- If the keys of the list are ordered, linear-time implementation is used,
1140 -- with the performance equal to 'fromDistinctAscList'.
1141 --
1142 -- > fromList [] == empty
1143 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1144 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1145
1146 -- For some reason, when 'singleton' is used in fromList or in
1147 -- create, it is not inlined, so we inline it manually.
1148 fromList :: Ord k => [(k,a)] -> Map k a
1149 fromList [] = Tip
1150 fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
1151 fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
1152 | otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1153 where
1154 not_ordered _ [] = False
1155 not_ordered kx ((ky,_) : _) = kx >= ky
1156 {-# INLINE not_ordered #-}
1157
1158 fromList' t0 xs = foldlStrict ins t0 xs
1159 where ins t (k,x) = insert k x t
1160
1161 go !_ t [] = t
1162 go _ t [(kx, x)] = x `seq` insertMax kx x t
1163 go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
1164 | otherwise = case create s xss of
1165 (r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1166 (r, _, ys) -> x `seq` fromList' (link kx x l r) ys
1167
1168 -- The create is returning a triple (tree, xs, ys). Both xs and ys
1169 -- represent not yet processed elements and only one of them can be nonempty.
1170 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
1171 -- and must be inserted using fromList'. Otherwise the keys have been
1172 -- ordered so far.
1173 create !_ [] = (Tip, [], [])
1174 create s xs@(xp : xss)
1175 | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
1176 | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
1177 | otherwise = case create (s `shiftR` 1) xs of
1178 res@(_, [], _) -> res
1179 (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
1180 (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
1181 | otherwise -> case create (s `shiftR` 1) yss of
1182 (r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
1183 #if __GLASGOW_HASKELL__
1184 {-# INLINABLE fromList #-}
1185 #endif
1186
1187 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1188 --
1189 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1190 -- > fromListWith (++) [] == empty
1191
1192 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1193 fromListWith f xs
1194 = fromListWithKey (\_ x y -> f x y) xs
1195 #if __GLASGOW_HASKELL__
1196 {-# INLINABLE fromListWith #-}
1197 #endif
1198
1199 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1200 --
1201 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1202 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1203 -- > fromListWithKey f [] == empty
1204
1205 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1206 fromListWithKey f xs
1207 = foldlStrict ins empty xs
1208 where
1209 ins t (k,x) = insertWithKey f k x t
1210 #if __GLASGOW_HASKELL__
1211 {-# INLINABLE fromListWithKey #-}
1212 #endif
1213
1214 {--------------------------------------------------------------------
1215 Building trees from ascending/descending lists can be done in linear time.
1216
1217 Note that if [xs] is ascending that:
1218 fromAscList xs == fromList xs
1219 fromAscListWith f xs == fromListWith f xs
1220 --------------------------------------------------------------------}
1221 -- | /O(n)/. Build a map from an ascending list in linear time.
1222 -- /The precondition (input list is ascending) is not checked./
1223 --
1224 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1225 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1226 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1227 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1228
1229 fromAscList :: Eq k => [(k,a)] -> Map k a
1230 fromAscList xs
1231 = fromAscListWithKey (\_ x _ -> x) xs
1232 #if __GLASGOW_HASKELL__
1233 {-# INLINABLE fromAscList #-}
1234 #endif
1235
1236 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1237 -- /The precondition (input list is ascending) is not checked./
1238 --
1239 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1240 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1241 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1242
1243 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1244 fromAscListWith f xs
1245 = fromAscListWithKey (\_ x y -> f x y) xs
1246 #if __GLASGOW_HASKELL__
1247 {-# INLINABLE fromAscListWith #-}
1248 #endif
1249
1250 -- | /O(n)/. Build a map from an ascending list in linear time with a
1251 -- combining function for equal keys.
1252 -- /The precondition (input list is ascending) is not checked./
1253 --
1254 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1255 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1256 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1257 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1258
1259 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1260 fromAscListWithKey f xs
1261 = fromDistinctAscList (combineEq f xs)
1262 where
1263 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1264 combineEq _ xs'
1265 = case xs' of
1266 [] -> []
1267 [x] -> [x]
1268 (x:xx) -> combineEq' x xx
1269
1270 combineEq' z [] = [z]
1271 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1272 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1273 | otherwise = z:combineEq' x xs'
1274 #if __GLASGOW_HASKELL__
1275 {-# INLINABLE fromAscListWithKey #-}
1276 #endif
1277
1278 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1279 -- /The precondition is not checked./
1280 --
1281 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1282 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1283 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1284
1285 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1286 -- create, it is not inlined, so we inline it manually.
1287 fromDistinctAscList :: [(k,a)] -> Map k a
1288 fromDistinctAscList [] = Tip
1289 fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1290 where
1291 go !_ t [] = t
1292 go s l ((kx, x) : xs) = case create s xs of
1293 (r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1294
1295 create !_ [] = (Tip, [])
1296 create s xs@(x' : xs')
1297 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1298 | otherwise = case create (s `shiftR` 1) xs of
1299 res@(_, []) -> res
1300 (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1301 (r, zs) -> y `seq` (link ky y l r, zs)