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