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