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