Add rewrite rule for alterF with pairs
[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 -- @
634 -- interactiveAlter :: Int -> Map Int String -> IO (Map Int String)
635 -- interactiveAlter k m = alterF f k m where
636 -- f Nothing -> do
637 -- putStrLn $ show k ++
638 -- " was not found in the map. Would you like to add it?"
639 -- getUserResponse1 :: IO (Maybe String)
640 -- f (Just old) -> do
641 -- putStrLn "The key is currently bound to " ++ show old ++
642 -- ". Would you like to change or delete it?"
643 -- getUserresponse2 :: IO (Maybe String)
644 -- @
645 --
646 -- 'alterF' is the most general operation for working with an individual
647 -- key that may or may not be in a given map. When used with trivial
648 -- functors like 'Identity' and 'Const', it is often slightly slower than
649 -- more specialized combinators like 'lookup' and 'insert'. However, when
650 -- the functor is non-trivial and key comparison is not particularly cheap,
651 -- it is the fastest way.
652 --
653 -- Note on rewrite rules:
654 --
655 -- This module includes GHC rewrite rules to optimize 'alterF' for the 'Const',
656 -- 'Identity', and @(,) b@ functors. In general, these rules improve
657 -- performance. The main exception is that when using 'Identity', deleting a
658 -- key that is already absent takes longer than it would without the rules. If
659 -- you expect this to occur a very large fraction of the time, you might
660 -- consider using a 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 "alterF/Pair" forall k (f :: Maybe a -> (b, Maybe a)) . alterF f k = atKeyPair k f
678 #-}
679
680 atKeyPair :: Ord k => k -> (Maybe a -> (b, Maybe a)) -> Map k a -> (b, Map k a)
681 atKeyPair k f t = atKeyWithLookup Strict k f t
682 {-# INLINABLE atKeyPair #-}
683
684 #if MIN_VERSION_base(4,8,0)
685 -- base 4.8 and above include Data.Functor.Identity, so we can
686 -- save a pretty decent amount of time by handling it specially.
687 {-# RULES
688 "alterF/Identity" forall k f . alterF f k = atKeyIdentity k f
689 #-}
690
691 atKeyIdentity :: Ord k => k -> (Maybe a -> Identity (Maybe a)) -> Map k a -> Identity (Map k a)
692 atKeyIdentity k f t = Identity $ atKeyPlain Strict k (coerce f) t
693 {-# INLINABLE atKeyIdentity #-}
694 #endif
695 #endif
696
697 {--------------------------------------------------------------------
698 Indexing
699 --------------------------------------------------------------------}
700
701 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
702 -- invalid index is used.
703 --
704 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
705 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
706 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
707 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
708 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
709 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
710 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
711 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
712
713 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
714 updateAt f i t = i `seq`
715 case t of
716 Tip -> error "Map.updateAt: index out of range"
717 Bin sx kx x l r -> case compare i sizeL of
718 LT -> balanceR kx x (updateAt f i l) r
719 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
720 EQ -> case f kx x of
721 Just x' -> x' `seq` Bin sx kx x' l r
722 Nothing -> glue l r
723 where
724 sizeL = size l
725
726 {--------------------------------------------------------------------
727 Minimal, Maximal
728 --------------------------------------------------------------------}
729
730 -- | /O(log n)/. Update the value at the minimal key.
731 --
732 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
733 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
734
735 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
736 updateMin f m
737 = updateMinWithKey (\_ x -> f x) m
738
739 -- | /O(log n)/. Update the value at the maximal key.
740 --
741 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
742 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
743
744 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
745 updateMax f m
746 = updateMaxWithKey (\_ x -> f x) m
747
748
749 -- | /O(log n)/. Update the value at the minimal key.
750 --
751 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
752 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
753
754 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
755 updateMinWithKey _ Tip = Tip
756 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
757 Nothing -> r
758 Just x' -> x' `seq` Bin sx kx x' Tip r
759 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
760
761 -- | /O(log n)/. Update the value at the maximal key.
762 --
763 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
764 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
765
766 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
767 updateMaxWithKey _ Tip = Tip
768 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
769 Nothing -> l
770 Just x' -> x' `seq` Bin sx kx x' l Tip
771 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
772
773 {--------------------------------------------------------------------
774 Union.
775 --------------------------------------------------------------------}
776
777 -- | The union of a list of maps, with a combining operation:
778 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
779 --
780 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
781 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
782
783 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
784 unionsWith f ts
785 = foldlStrict (unionWith f) empty ts
786 #if __GLASGOW_HASKELL__
787 {-# INLINABLE unionsWith #-}
788 #endif
789
790 {--------------------------------------------------------------------
791 Union with a combining function
792 --------------------------------------------------------------------}
793 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
794 --
795 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
796
797 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
798 unionWith f m1 m2
799 = unionWithKey (\_ x y -> f x y) m1 m2
800 #if __GLASGOW_HASKELL__
801 {-# INLINABLE unionWith #-}
802 #endif
803
804 -- | /O(n+m)/.
805 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
806 --
807 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
808 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
809
810 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
811 unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
812 #if __GLASGOW_HASKELL__
813 {-# INLINABLE unionWithKey #-}
814 #endif
815
816 {--------------------------------------------------------------------
817 Difference
818 --------------------------------------------------------------------}
819
820 -- | /O(n+m)/. Difference with a combining function.
821 -- When two equal keys are
822 -- encountered, the combining function is applied to the values of these keys.
823 -- If it returns 'Nothing', the element is discarded (proper set difference). If
824 -- it returns (@'Just' y@), the element is updated with a new value @y@.
825 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
826 --
827 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
828 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
829 -- > == singleton 3 "b:B"
830
831 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
832 differenceWith f m1 m2
833 = differenceWithKey (\_ x y -> f x y) m1 m2
834 #if __GLASGOW_HASKELL__
835 {-# INLINABLE differenceWith #-}
836 #endif
837
838 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
839 -- encountered, the combining function is applied to the key and both values.
840 -- If it returns 'Nothing', the element is discarded (proper set difference). If
841 -- it returns (@'Just' y@), the element is updated with a new value @y@.
842 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
843 --
844 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
845 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
846 -- > == singleton 3 "3:b|B"
847
848 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
849 differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
850 #if __GLASGOW_HASKELL__
851 {-# INLINABLE differenceWithKey #-}
852 #endif
853
854
855 {--------------------------------------------------------------------
856 Intersection
857 --------------------------------------------------------------------}
858
859 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
860 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
861 --
862 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
863
864 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
865 intersectionWith f m1 m2
866 = intersectionWithKey (\_ x y -> f x y) m1 m2
867 #if __GLASGOW_HASKELL__
868 {-# INLINABLE intersectionWith #-}
869 #endif
870
871 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
872 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
873 --
874 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
875 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
876
877
878 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
879 intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
880 #if __GLASGOW_HASKELL__
881 {-# INLINABLE intersectionWithKey #-}
882 #endif
883
884
885 {--------------------------------------------------------------------
886 MergeWithKey
887 --------------------------------------------------------------------}
888
889 -- | /O(n+m)/. A high-performance universal combining function. This function
890 -- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
891 -- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
892 -- used to define other custom combine functions.
893 --
894 -- Please make sure you know what is going on when using 'mergeWithKey',
895 -- otherwise you can be surprised by unexpected code growth or even
896 -- corruption of the data structure.
897 --
898 -- When 'mergeWithKey' is given three arguments, it is inlined to the call
899 -- site. You should therefore use 'mergeWithKey' only to define your custom
900 -- combining functions. For example, you could define 'unionWithKey',
901 -- 'differenceWithKey' and 'intersectionWithKey' as
902 --
903 -- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
904 -- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
905 -- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
906 --
907 -- When calling @'mergeWithKey' combine only1 only2@, a function combining two
908 -- 'Map's is created, such that
909 --
910 -- * if a key is present in both maps, it is passed with both corresponding
911 -- values to the @combine@ function. Depending on the result, the key is either
912 -- present in the result with specified value, or is left out;
913 --
914 -- * a nonempty subtree present only in the first map is passed to @only1@ and
915 -- the output is added to the result;
916 --
917 -- * a nonempty subtree present only in the second map is passed to @only2@ and
918 -- the output is added to the result.
919 --
920 -- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
921 -- The values can be modified arbitrarily. Most common variants of @only1@ and
922 -- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
923 -- @'filterWithKey' f@ could be used for any @f@.
924
925 mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
926 -> Map k a -> Map k b -> Map k c
927 mergeWithKey f g1 g2 = go
928 where
929 go Tip t2 = g2 t2
930 go t1 Tip = g1 t1
931 go t1 t2 = hedgeMerge NothingS NothingS t1 t2
932
933 hedgeMerge _ _ t1 Tip = g1 t1
934 hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r)
935 hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
936 (found, trim_t2) = trimLookupLo kx bhi t2
937 r' = hedgeMerge bmi bhi r trim_t2
938 in case found of
939 Nothing -> case g1 (singleton kx x) of
940 Tip -> merge l' r'
941 (Bin _ _ x' Tip Tip) -> link kx x' l' r'
942 _ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
943 Just x2 -> case f kx x x2 of
944 Nothing -> merge l' r'
945 Just x' -> x' `seq` link kx x' l' r'
946 where bmi = JustS kx
947 {-# INLINE mergeWithKey #-}
948
949 {--------------------------------------------------------------------
950 Filter and partition
951 --------------------------------------------------------------------}
952
953 -- | /O(n)/. Map values and collect the 'Just' results.
954 --
955 -- > let f x = if x == "a" then Just "new a" else Nothing
956 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
957
958 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
959 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
960
961 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
962 --
963 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
964 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
965
966 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
967 mapMaybeWithKey _ Tip = Tip
968 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
969 Just y -> y `seq` link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
970 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
971
972 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
973 --
974 -- > let f a = if a < "c" then Left a else Right a
975 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
976 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
977 -- >
978 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
979 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
980
981 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
982 mapEither f m
983 = mapEitherWithKey (\_ x -> f x) m
984
985 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
986 --
987 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
988 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
989 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
990 -- >
991 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
992 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
993
994 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
995 mapEitherWithKey f0 t0 = toPair $ go f0 t0
996 where
997 go _ Tip = (Tip :*: Tip)
998 go f (Bin _ kx x l r) = case f kx x of
999 Left y -> y `seq` (link kx y l1 r1 :*: merge l2 r2)
1000 Right z -> z `seq` (merge l1 r1 :*: link kx z l2 r2)
1001 where
1002 (l1 :*: l2) = go f l
1003 (r1 :*: r2) = go f r
1004
1005 {--------------------------------------------------------------------
1006 Mapping
1007 --------------------------------------------------------------------}
1008 -- | /O(n)/. Map a function over all values in the map.
1009 --
1010 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
1011
1012 map :: (a -> b) -> Map k a -> Map k b
1013 map _ Tip = Tip
1014 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)
1015 #ifdef __GLASGOW_HASKELL__
1016 {-# NOINLINE [1] map #-}
1017 {-# RULES
1018 "map/map" forall f g xs . map f (map g xs) = map (f . g) xs
1019 #-}
1020 #endif
1021 #if __GLASGOW_HASKELL__ >= 709
1022 -- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
1023 {-# RULES
1024 "mapSeq/coerce" map coerce = coerce
1025 #-}
1026 #endif
1027
1028 -- | /O(n)/. Map a function over all values in the map.
1029 --
1030 -- > let f key x = (show key) ++ ":" ++ x
1031 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
1032
1033 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
1034 mapWithKey _ Tip = Tip
1035 mapWithKey f (Bin sx kx x l r) =
1036 let x' = f kx x
1037 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
1038
1039 #ifdef __GLASGOW_HASKELL__
1040 {-# NOINLINE [1] mapWithKey #-}
1041 {-# RULES
1042 "mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
1043 mapWithKey (\k a -> f k (g k a)) xs
1044 "mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
1045 mapWithKey (\k a -> f k (g a)) xs
1046 "map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
1047 mapWithKey (\k a -> f (g k a)) xs
1048 #-}
1049 #endif
1050
1051 -- | /O(n)/.
1052 -- @'traverseWithKey' f m == 'fromList' <$> 'traverse' (\(k, v) -> (\v' -> v' `seq` (k,v')) <$> f k v) ('toList' m)@
1053 -- That is, it behaves much like a regular 'traverse' except that the traversing
1054 -- function also has access to the key associated with a value and the values are
1055 -- forced before they are installed in the result map.
1056 --
1057 -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')])
1058 -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == Nothing
1059 traverseWithKey :: Applicative t => (k -> a -> t b) -> Map k a -> t (Map k b)
1060 traverseWithKey f = go
1061 where
1062 go Tip = pure Tip
1063 go (Bin 1 k v _ _) = (\ !v' -> Bin 1 k v' Tip Tip) <$> f k v
1064 go (Bin s k v l r) = (\ l' !v' r' -> Bin s k v' l' r') <$> go l <*> f k v <*> go r
1065 {-# INLINE traverseWithKey #-}
1066
1067 -- | /O(n)/. The function 'mapAccum' threads an accumulating
1068 -- argument through the map in ascending order of keys.
1069 --
1070 -- > let f a b = (a ++ b, b ++ "X")
1071 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
1072
1073 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1074 mapAccum f a m
1075 = mapAccumWithKey (\a' _ x' -> f a' x') a m
1076
1077 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
1078 -- argument through the map in ascending order of keys.
1079 --
1080 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
1081 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
1082
1083 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1084 mapAccumWithKey f a t
1085 = mapAccumL f a t
1086
1087 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
1088 -- argument through the map in ascending order of keys.
1089 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1090 mapAccumL _ a Tip = (a,Tip)
1091 mapAccumL f a (Bin sx kx x l r) =
1092 let (a1,l') = mapAccumL f a l
1093 (a2,x') = f a1 kx x
1094 (a3,r') = mapAccumL f a2 r
1095 in x' `seq` (a3,Bin sx kx x' l' r')
1096
1097 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
1098 -- argument through the map in descending order of keys.
1099 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1100 mapAccumRWithKey _ a Tip = (a,Tip)
1101 mapAccumRWithKey f a (Bin sx kx x l r) =
1102 let (a1,r') = mapAccumRWithKey f a r
1103 (a2,x') = f a1 kx x
1104 (a3,l') = mapAccumRWithKey f a2 l
1105 in x' `seq` (a3,Bin sx kx x' l' r')
1106
1107 -- | /O(n*log n)/.
1108 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1109 --
1110 -- The size of the result may be smaller if @f@ maps two or more distinct
1111 -- keys to the same new key. In this case the associated values will be
1112 -- combined using @c@.
1113 --
1114 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1115 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1116
1117 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1118 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
1119 #if __GLASGOW_HASKELL__
1120 {-# INLINABLE mapKeysWith #-}
1121 #endif
1122
1123 {--------------------------------------------------------------------
1124 Conversions
1125 --------------------------------------------------------------------}
1126
1127 -- | /O(n)/. Build a map from a set of keys and a function which for each key
1128 -- computes its value.
1129 --
1130 -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
1131 -- > fromSet undefined Data.Set.empty == empty
1132
1133 fromSet :: (k -> a) -> Set.Set k -> Map k a
1134 fromSet _ Set.Tip = Tip
1135 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)
1136
1137 {--------------------------------------------------------------------
1138 Lists
1139 use [foldlStrict] to reduce demand on the control-stack
1140 --------------------------------------------------------------------}
1141 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1142 -- If the list contains more than one value for the same key, the last value
1143 -- for the key is retained.
1144 --
1145 -- If the keys of the list are ordered, linear-time implementation is used,
1146 -- with the performance equal to 'fromDistinctAscList'.
1147 --
1148 -- > fromList [] == empty
1149 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1150 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1151
1152 -- For some reason, when 'singleton' is used in fromList or in
1153 -- create, it is not inlined, so we inline it manually.
1154 fromList :: Ord k => [(k,a)] -> Map k a
1155 fromList [] = Tip
1156 fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
1157 fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
1158 | otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1159 where
1160 not_ordered _ [] = False
1161 not_ordered kx ((ky,_) : _) = kx >= ky
1162 {-# INLINE not_ordered #-}
1163
1164 fromList' t0 xs = foldlStrict ins t0 xs
1165 where ins t (k,x) = insert k x t
1166
1167 go !_ t [] = t
1168 go _ t [(kx, x)] = x `seq` insertMax kx x t
1169 go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
1170 | otherwise = case create s xss of
1171 (r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1172 (r, _, ys) -> x `seq` fromList' (link kx x l r) ys
1173
1174 -- The create is returning a triple (tree, xs, ys). Both xs and ys
1175 -- represent not yet processed elements and only one of them can be nonempty.
1176 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
1177 -- and must be inserted using fromList'. Otherwise the keys have been
1178 -- ordered so far.
1179 create !_ [] = (Tip, [], [])
1180 create s xs@(xp : xss)
1181 | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
1182 | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
1183 | otherwise = case create (s `shiftR` 1) xs of
1184 res@(_, [], _) -> res
1185 (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
1186 (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
1187 | otherwise -> case create (s `shiftR` 1) yss of
1188 (r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
1189 #if __GLASGOW_HASKELL__
1190 {-# INLINABLE fromList #-}
1191 #endif
1192
1193 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1194 --
1195 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1196 -- > fromListWith (++) [] == empty
1197
1198 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1199 fromListWith f xs
1200 = fromListWithKey (\_ x y -> f x y) xs
1201 #if __GLASGOW_HASKELL__
1202 {-# INLINABLE fromListWith #-}
1203 #endif
1204
1205 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1206 --
1207 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1208 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1209 -- > fromListWithKey f [] == empty
1210
1211 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1212 fromListWithKey f xs
1213 = foldlStrict ins empty xs
1214 where
1215 ins t (k,x) = insertWithKey f k x t
1216 #if __GLASGOW_HASKELL__
1217 {-# INLINABLE fromListWithKey #-}
1218 #endif
1219
1220 {--------------------------------------------------------------------
1221 Building trees from ascending/descending lists can be done in linear time.
1222
1223 Note that if [xs] is ascending that:
1224 fromAscList xs == fromList xs
1225 fromAscListWith f xs == fromListWith f xs
1226 --------------------------------------------------------------------}
1227 -- | /O(n)/. Build a map from an ascending list in linear time.
1228 -- /The precondition (input list is ascending) is not checked./
1229 --
1230 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1231 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1232 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1233 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1234
1235 fromAscList :: Eq k => [(k,a)] -> Map k a
1236 fromAscList xs
1237 = fromAscListWithKey (\_ x _ -> x) xs
1238 #if __GLASGOW_HASKELL__
1239 {-# INLINABLE fromAscList #-}
1240 #endif
1241
1242 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1243 -- /The precondition (input list is ascending) is not checked./
1244 --
1245 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1246 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1247 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1248
1249 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1250 fromAscListWith f xs
1251 = fromAscListWithKey (\_ x y -> f x y) xs
1252 #if __GLASGOW_HASKELL__
1253 {-# INLINABLE fromAscListWith #-}
1254 #endif
1255
1256 -- | /O(n)/. Build a map from an ascending list in linear time with a
1257 -- combining function for equal keys.
1258 -- /The precondition (input list is ascending) is not checked./
1259 --
1260 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1261 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1262 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1263 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1264
1265 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1266 fromAscListWithKey f xs
1267 = fromDistinctAscList (combineEq f xs)
1268 where
1269 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1270 combineEq _ xs'
1271 = case xs' of
1272 [] -> []
1273 [x] -> [x]
1274 (x:xx) -> combineEq' x xx
1275
1276 combineEq' z [] = [z]
1277 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1278 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1279 | otherwise = z:combineEq' x xs'
1280 #if __GLASGOW_HASKELL__
1281 {-# INLINABLE fromAscListWithKey #-}
1282 #endif
1283
1284 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1285 -- /The precondition is not checked./
1286 --
1287 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1288 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1289 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1290
1291 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1292 -- create, it is not inlined, so we inline it manually.
1293 fromDistinctAscList :: [(k,a)] -> Map k a
1294 fromDistinctAscList [] = Tip
1295 fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1296 where
1297 go !_ t [] = t
1298 go s l ((kx, x) : xs) = case create s xs of
1299 (r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1300
1301 create !_ [] = (Tip, [])
1302 create s xs@(x' : xs')
1303 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1304 | otherwise = case create (s `shiftR` 1) xs of
1305 res@(_, []) -> res
1306 (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1307 (r, zs) -> y `seq` (link ky y l r, zs)