Merge pull request #305 from treeowl/restriction
[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(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
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 m1 m2
804 = unionWithKey (\_ x y -> f x y) m1 m2
805 #if __GLASGOW_HASKELL__
806 {-# INLINABLE unionWith #-}
807 #endif
808
809 -- | /O(n+m)/.
810 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
811 --
812 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
813 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
814
815 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
816 unionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) id id t1 t2
817 #if __GLASGOW_HASKELL__
818 {-# INLINABLE unionWithKey #-}
819 #endif
820
821 {--------------------------------------------------------------------
822 Difference
823 --------------------------------------------------------------------}
824
825 -- | /O(n+m)/. Difference with a combining function.
826 -- When two equal keys are
827 -- encountered, the combining function is applied to the values of these keys.
828 -- If it returns 'Nothing', the element is discarded (proper set difference). If
829 -- it returns (@'Just' y@), the element is updated with a new value @y@.
830 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
831 --
832 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
833 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
834 -- > == singleton 3 "b:B"
835
836 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
837 differenceWith f m1 m2
838 = differenceWithKey (\_ x y -> f x y) m1 m2
839 #if __GLASGOW_HASKELL__
840 {-# INLINABLE differenceWith #-}
841 #endif
842
843 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
844 -- encountered, the combining function is applied to the key and both values.
845 -- If it returns 'Nothing', the element is discarded (proper set difference). If
846 -- it returns (@'Just' y@), the element is updated with a new value @y@.
847 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
848 --
849 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
850 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
851 -- > == singleton 3 "3:b|B"
852
853 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
854 differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2
855 #if __GLASGOW_HASKELL__
856 {-# INLINABLE differenceWithKey #-}
857 #endif
858
859
860 {--------------------------------------------------------------------
861 Intersection
862 --------------------------------------------------------------------}
863
864 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
865 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
866 --
867 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
868
869 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
870 intersectionWith f m1 m2
871 = intersectionWithKey (\_ x y -> f x y) m1 m2
872 #if __GLASGOW_HASKELL__
873 {-# INLINABLE intersectionWith #-}
874 #endif
875
876 -- | /O(n+m)/. Intersection with a combining function. The implementation uses
877 -- an efficient /hedge/ algorithm comparable with /hedge-union/.
878 --
879 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
880 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
881
882
883 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
884 intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just $ f k x1 x2) (const Tip) (const Tip) t1 t2
885 #if __GLASGOW_HASKELL__
886 {-# INLINABLE intersectionWithKey #-}
887 #endif
888
889
890 {--------------------------------------------------------------------
891 MergeWithKey
892 --------------------------------------------------------------------}
893
894 -- | /O(n+m)/. A high-performance universal combining function. This function
895 -- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
896 -- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
897 -- used to define other custom combine functions.
898 --
899 -- Please make sure you know what is going on when using 'mergeWithKey',
900 -- otherwise you can be surprised by unexpected code growth or even
901 -- corruption of the data structure.
902 --
903 -- When 'mergeWithKey' is given three arguments, it is inlined to the call
904 -- site. You should therefore use 'mergeWithKey' only to define your custom
905 -- combining functions. For example, you could define 'unionWithKey',
906 -- 'differenceWithKey' and 'intersectionWithKey' as
907 --
908 -- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
909 -- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
910 -- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
911 --
912 -- When calling @'mergeWithKey' combine only1 only2@, a function combining two
913 -- 'Map's is created, such that
914 --
915 -- * if a key is present in both maps, it is passed with both corresponding
916 -- values to the @combine@ function. Depending on the result, the key is either
917 -- present in the result with specified value, or is left out;
918 --
919 -- * a nonempty subtree present only in the first map is passed to @only1@ and
920 -- the output is added to the result;
921 --
922 -- * a nonempty subtree present only in the second map is passed to @only2@ and
923 -- the output is added to the result.
924 --
925 -- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
926 -- The values can be modified arbitrarily. Most common variants of @only1@ and
927 -- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
928 -- @'filterWithKey' f@ could be used for any @f@.
929
930 mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
931 -> Map k a -> Map k b -> Map k c
932 mergeWithKey f g1 g2 = go
933 where
934 go Tip t2 = g2 t2
935 go t1 Tip = g1 t1
936 go t1 t2 = hedgeMerge NothingS NothingS t1 t2
937
938 hedgeMerge _ _ t1 Tip = g1 t1
939 hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ link kx x (filterGt blo l) (filterLt bhi r)
940 hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
941 (found, trim_t2) = trimLookupLo kx bhi t2
942 r' = hedgeMerge bmi bhi r trim_t2
943 in case found of
944 Nothing -> case g1 (singleton kx x) of
945 Tip -> merge l' r'
946 (Bin _ _ x' Tip Tip) -> link kx x' l' r'
947 _ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
948 Just x2 -> case f kx x x2 of
949 Nothing -> merge l' r'
950 Just x' -> x' `seq` link kx x' l' r'
951 where bmi = JustS kx
952 {-# INLINE mergeWithKey #-}
953
954 {--------------------------------------------------------------------
955 Filter and partition
956 --------------------------------------------------------------------}
957
958 -- | /O(n)/. Map values and collect the 'Just' results.
959 --
960 -- > let f x = if x == "a" then Just "new a" else Nothing
961 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
962
963 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
964 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
965
966 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
967 --
968 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
969 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
970
971 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
972 mapMaybeWithKey _ Tip = Tip
973 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
974 Just y -> y `seq` link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
975 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
976
977 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
978 --
979 -- > let f a = if a < "c" then Left a else Right a
980 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
981 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
982 -- >
983 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
984 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
985
986 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
987 mapEither f m
988 = mapEitherWithKey (\_ x -> f x) m
989
990 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
991 --
992 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
993 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
994 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
995 -- >
996 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
997 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
998
999 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
1000 mapEitherWithKey f0 t0 = toPair $ go f0 t0
1001 where
1002 go _ Tip = (Tip :*: Tip)
1003 go f (Bin _ kx x l r) = case f kx x of
1004 Left y -> y `seq` (link kx y l1 r1 :*: merge l2 r2)
1005 Right z -> z `seq` (merge l1 r1 :*: link kx z l2 r2)
1006 where
1007 (l1 :*: l2) = go f l
1008 (r1 :*: r2) = go f r
1009
1010 {--------------------------------------------------------------------
1011 Mapping
1012 --------------------------------------------------------------------}
1013 -- | /O(n)/. Map a function over all values in the map.
1014 --
1015 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
1016
1017 map :: (a -> b) -> Map k a -> Map k b
1018 map f = go
1019 where
1020 go Tip = Tip
1021 go (Bin sx kx x l r) = let !x' = f x in Bin sx kx x' (go l) (go r)
1022 -- We use `go` to let `map` inline. This is important if `f` is a constant
1023 -- function.
1024
1025 #ifdef __GLASGOW_HASKELL__
1026 {-# NOINLINE [1] map #-}
1027 {-# RULES
1028 "map/map" forall f g xs . map f (map g xs) = map (f . g) xs
1029 #-}
1030 #endif
1031 #if __GLASGOW_HASKELL__ >= 709
1032 -- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
1033 {-# RULES
1034 "mapSeq/coerce" map coerce = coerce
1035 #-}
1036 #endif
1037
1038 -- | /O(n)/. Map a function over all values in the map.
1039 --
1040 -- > let f key x = (show key) ++ ":" ++ x
1041 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
1042
1043 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
1044 mapWithKey _ Tip = Tip
1045 mapWithKey f (Bin sx kx x l r) =
1046 let x' = f kx x
1047 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
1048
1049 #ifdef __GLASGOW_HASKELL__
1050 {-# NOINLINE [1] mapWithKey #-}
1051 {-# RULES
1052 "mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
1053 mapWithKey (\k a -> f k (g k a)) xs
1054 "mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
1055 mapWithKey (\k a -> f k (g a)) xs
1056 "map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
1057 mapWithKey (\k a -> f (g k a)) xs
1058 #-}
1059 #endif
1060
1061 -- | /O(n)/.
1062 -- @'traverseWithKey' f m == 'fromList' <$> 'traverse' (\(k, v) -> (\v' -> v' `seq` (k,v')) <$> f k v) ('toList' m)@
1063 -- That is, it behaves much like a regular 'traverse' except that the traversing
1064 -- function also has access to the key associated with a value and the values are
1065 -- forced before they are installed in the result map.
1066 --
1067 -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a'), (5, 'e')]) == Just (fromList [(1, 'b'), (5, 'f')])
1068 -- > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')]) == Nothing
1069 traverseWithKey :: Applicative t => (k -> a -> t b) -> Map k a -> t (Map k b)
1070 traverseWithKey f = go
1071 where
1072 go Tip = pure Tip
1073 go (Bin 1 k v _ _) = (\ !v' -> Bin 1 k v' Tip Tip) <$> f k v
1074 go (Bin s k v l r) = (\ l' !v' r' -> Bin s k v' l' r') <$> go l <*> f k v <*> go r
1075 {-# INLINE traverseWithKey #-}
1076
1077 -- | /O(n)/. The function 'mapAccum' threads an accumulating
1078 -- argument through the map in ascending order of keys.
1079 --
1080 -- > let f a b = (a ++ b, b ++ "X")
1081 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
1082
1083 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1084 mapAccum f a m
1085 = mapAccumWithKey (\a' _ x' -> f a' x') a m
1086
1087 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
1088 -- argument through the map in ascending order of keys.
1089 --
1090 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
1091 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
1092
1093 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1094 mapAccumWithKey f a t
1095 = mapAccumL f a t
1096
1097 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
1098 -- argument through the map in ascending order of keys.
1099 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1100 mapAccumL _ a Tip = (a,Tip)
1101 mapAccumL f a (Bin sx kx x l r) =
1102 let (a1,l') = mapAccumL f a l
1103 (a2,x') = f a1 kx x
1104 (a3,r') = mapAccumL f a2 r
1105 in x' `seq` (a3,Bin sx kx x' l' r')
1106
1107 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
1108 -- argument through the map in descending order of keys.
1109 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1110 mapAccumRWithKey _ a Tip = (a,Tip)
1111 mapAccumRWithKey f a (Bin sx kx x l r) =
1112 let (a1,r') = mapAccumRWithKey f a r
1113 (a2,x') = f a1 kx x
1114 (a3,l') = mapAccumRWithKey f a2 l
1115 in x' `seq` (a3,Bin sx kx x' l' r')
1116
1117 -- | /O(n*log n)/.
1118 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1119 --
1120 -- The size of the result may be smaller if @f@ maps two or more distinct
1121 -- keys to the same new key. In this case the associated values will be
1122 -- combined using @c@.
1123 --
1124 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1125 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1126
1127 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1128 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
1129 #if __GLASGOW_HASKELL__
1130 {-# INLINABLE mapKeysWith #-}
1131 #endif
1132
1133 {--------------------------------------------------------------------
1134 Conversions
1135 --------------------------------------------------------------------}
1136
1137 -- | /O(n)/. Build a map from a set of keys and a function which for each key
1138 -- computes its value.
1139 --
1140 -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
1141 -- > fromSet undefined Data.Set.empty == empty
1142
1143 fromSet :: (k -> a) -> Set.Set k -> Map k a
1144 fromSet _ Set.Tip = Tip
1145 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)
1146
1147 {--------------------------------------------------------------------
1148 Lists
1149 use [foldlStrict] to reduce demand on the control-stack
1150 --------------------------------------------------------------------}
1151 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1152 -- If the list contains more than one value for the same key, the last value
1153 -- for the key is retained.
1154 --
1155 -- If the keys of the list are ordered, linear-time implementation is used,
1156 -- with the performance equal to 'fromDistinctAscList'.
1157 --
1158 -- > fromList [] == empty
1159 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1160 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1161
1162 -- For some reason, when 'singleton' is used in fromList or in
1163 -- create, it is not inlined, so we inline it manually.
1164 fromList :: Ord k => [(k,a)] -> Map k a
1165 fromList [] = Tip
1166 fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
1167 fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
1168 | otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1169 where
1170 not_ordered _ [] = False
1171 not_ordered kx ((ky,_) : _) = kx >= ky
1172 {-# INLINE not_ordered #-}
1173
1174 fromList' t0 xs = foldlStrict ins t0 xs
1175 where ins t (k,x) = insert k x t
1176
1177 go !_ t [] = t
1178 go _ t [(kx, x)] = x `seq` insertMax kx x t
1179 go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
1180 | otherwise = case create s xss of
1181 (r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1182 (r, _, ys) -> x `seq` fromList' (link kx x l r) ys
1183
1184 -- The create is returning a triple (tree, xs, ys). Both xs and ys
1185 -- represent not yet processed elements and only one of them can be nonempty.
1186 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
1187 -- and must be inserted using fromList'. Otherwise the keys have been
1188 -- ordered so far.
1189 create !_ [] = (Tip, [], [])
1190 create s xs@(xp : xss)
1191 | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
1192 | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
1193 | otherwise = case create (s `shiftR` 1) xs of
1194 res@(_, [], _) -> res
1195 (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
1196 (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
1197 | otherwise -> case create (s `shiftR` 1) yss of
1198 (r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
1199 #if __GLASGOW_HASKELL__
1200 {-# INLINABLE fromList #-}
1201 #endif
1202
1203 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1204 --
1205 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1206 -- > fromListWith (++) [] == empty
1207
1208 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1209 fromListWith f xs
1210 = fromListWithKey (\_ x y -> f x y) xs
1211 #if __GLASGOW_HASKELL__
1212 {-# INLINABLE fromListWith #-}
1213 #endif
1214
1215 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1216 --
1217 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1218 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1219 -- > fromListWithKey f [] == empty
1220
1221 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1222 fromListWithKey f xs
1223 = foldlStrict ins empty xs
1224 where
1225 ins t (k,x) = insertWithKey f k x t
1226 #if __GLASGOW_HASKELL__
1227 {-# INLINABLE fromListWithKey #-}
1228 #endif
1229
1230 {--------------------------------------------------------------------
1231 Building trees from ascending/descending lists can be done in linear time.
1232
1233 Note that if [xs] is ascending then:
1234 fromAscList xs == fromList xs
1235 fromAscListWith f xs == fromListWith f xs
1236
1237 If [xs] is descending then:
1238 fromDescList xs == fromList xs
1239 fromDescListWith f xs == fromListWith f xs
1240 --------------------------------------------------------------------}
1241
1242 -- | /O(n)/. Build a map from an ascending list in linear time.
1243 -- /The precondition (input list is ascending) is not checked./
1244 --
1245 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1246 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1247 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1248 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1249 fromAscList :: Eq k => [(k,a)] -> Map k a
1250 fromAscList xs
1251 = fromAscListWithKey (\_ x _ -> x) xs
1252 #if __GLASGOW_HASKELL__
1253 {-# INLINABLE fromAscList #-}
1254 #endif
1255
1256 -- | /O(n)/. Build a map from a descending list in linear time.
1257 -- /The precondition (input list is descending) is not checked./
1258 --
1259 -- > fromDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")]
1260 -- > fromDescList [(5,"a"), (5,"b"), (3,"a")] == fromList [(3, "b"), (5, "b")]
1261 -- > valid (fromDescList [(5,"a"), (5,"b"), (3,"b")]) == True
1262 -- > valid (fromDescList [(5,"a"), (3,"b"), (5,"b")]) == False
1263 fromDescList :: Eq k => [(k,a)] -> Map k a
1264 fromDescList xs
1265 = fromDescListWithKey (\_ x _ -> x) xs
1266 #if __GLASGOW_HASKELL__
1267 {-# INLINABLE fromDescList #-}
1268 #endif
1269
1270 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1271 -- /The precondition (input list is ascending) is not checked./
1272 --
1273 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1274 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1275 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1276
1277 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1278 fromAscListWith f xs
1279 = fromAscListWithKey (\_ x y -> f x y) xs
1280 #if __GLASGOW_HASKELL__
1281 {-# INLINABLE fromAscListWith #-}
1282 #endif
1283
1284 -- | /O(n)/. Build a map from a descending list in linear time with a combining function for equal keys.
1285 -- /The precondition (input list is descending) is not checked./
1286 --
1287 -- > fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "ba")]
1288 -- > valid (fromDescListWith (++) [(5,"a"), (5,"b"), (3,"b")]) == True
1289 -- > valid (fromDescListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1290
1291 fromDescListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1292 fromDescListWith f xs
1293 = fromDescListWithKey (\_ x y -> f x y) xs
1294 #if __GLASGOW_HASKELL__
1295 {-# INLINABLE fromDescListWith #-}
1296 #endif
1297
1298 -- | /O(n)/. Build a map from an ascending list in linear time with a
1299 -- combining function for equal keys.
1300 -- /The precondition (input list is ascending) is not checked./
1301 --
1302 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1303 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1304 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1305 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1306
1307 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1308 fromAscListWithKey f xs
1309 = fromDistinctAscList (combineEq f xs)
1310 where
1311 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1312 combineEq _ xs'
1313 = case xs' of
1314 [] -> []
1315 [x] -> [x]
1316 (x:xx) -> combineEq' x xx
1317
1318 combineEq' z [] = [z]
1319 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1320 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1321 | otherwise = z:combineEq' x xs'
1322 #if __GLASGOW_HASKELL__
1323 {-# INLINABLE fromAscListWithKey #-}
1324 #endif
1325
1326 -- | /O(n)/. Build a map from a descending list in linear time with a
1327 -- combining function for equal keys.
1328 -- /The precondition (input list is descending) is not checked./
1329 --
1330 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1331 -- > fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1332 -- > valid (fromDescListWithKey f [(5,"a"), (5,"b"), (5,"b"), (3,"b")]) == True
1333 -- > valid (fromDescListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1334
1335 fromDescListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1336 fromDescListWithKey f xs
1337 = fromDistinctDescList (combineEq f xs)
1338 where
1339 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1340 combineEq _ xs'
1341 = case xs' of
1342 [] -> []
1343 [x] -> [x]
1344 (x:xx) -> combineEq' x xx
1345
1346 combineEq' z [] = [z]
1347 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1348 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1349 | otherwise = z:combineEq' x xs'
1350 #if __GLASGOW_HASKELL__
1351 {-# INLINABLE fromDescListWithKey #-}
1352 #endif
1353
1354 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1355 -- /The precondition is not checked./
1356 --
1357 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1358 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1359 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1360
1361 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1362 -- create, it is not inlined, so we inline it manually.
1363 fromDistinctAscList :: [(k,a)] -> Map k a
1364 fromDistinctAscList [] = Tip
1365 fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1366 where
1367 go !_ t [] = t
1368 go s l ((kx, x) : xs) = case create s xs of
1369 (r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1370
1371 create !_ [] = (Tip, [])
1372 create s xs@(x' : xs')
1373 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1374 | otherwise = case create (s `shiftR` 1) xs of
1375 res@(_, []) -> res
1376 (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1377 (r, zs) -> y `seq` (link ky y l r, zs)
1378
1379 -- | /O(n)/. Build a map from a descending list of distinct elements in linear time.
1380 -- /The precondition is not checked./
1381 --
1382 -- > fromDistinctDescList [(5,"a"), (3,"b")] == fromList [(3, "b"), (5, "a")]
1383 -- > valid (fromDistinctDescList [(5,"a"), (3,"b")]) == True
1384 -- > valid (fromDistinctDescList [(5,"a"), (3,"b"), (3,"a")]) == False
1385
1386 -- For some reason, when 'singleton' is used in fromDistinctDescList or in
1387 -- create, it is not inlined, so we inline it manually.
1388 fromDistinctDescList :: [(k,a)] -> Map k a
1389 fromDistinctDescList [] = Tip
1390 fromDistinctDescList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1391 where
1392 go !_ t [] = t
1393 go s r ((kx, x) : xs) = case create s xs of
1394 (l, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1395
1396 create !_ [] = (Tip, [])
1397 create s xs@(x' : xs')
1398 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1399 | otherwise = case create (s `shiftR` 1) xs of
1400 res@(_, []) -> res
1401 (r, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1402 (l, zs) -> y `seq` (link ky y l r, zs)