Add Map.mergeWithKey.
[packages/containers.git] / Data / Map / Strict.hs
1 {-# LANGUAGE CPP #-}
2 #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
3 {-# LANGUAGE Safe #-}
4 #endif
5 -----------------------------------------------------------------------------
6 -- |
7 -- Module : Data.Map.Strict
8 -- Copyright : (c) Daan Leijen 2002
9 -- (c) Andriy Palamarchuk 2008
10 -- License : BSD-style
11 -- Maintainer : libraries@haskell.org
12 -- Stability : provisional
13 -- Portability : portable
14 --
15 -- An efficient implementation of ordered maps from keys to values
16 -- (dictionaries).
17 --
18 -- API of this module is strict in both the keys and the values.
19 -- If you need value-lazy maps, use 'Data.Map.Lazy' instead.
20 -- The 'Map' type is shared between the lazy and strict modules,
21 -- meaning that the same 'Map' value can be passed to functions in
22 -- both modules (although that is rarely needed).
23 --
24 -- These modules are intended to be imported qualified, to avoid name
25 -- clashes with Prelude functions, e.g.
26 --
27 -- > import qualified Data.Map.Strict as Map
28 --
29 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
30 -- trees of /bounded balance/) as described by:
31 --
32 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
33 -- Journal of Functional Programming 3(4):553-562, October 1993,
34 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
35 --
36 -- * J. Nievergelt and E.M. Reingold,
37 -- \"/Binary search trees of bounded balance/\",
38 -- SIAM journal of computing 2(1), March 1973.
39 --
40 -- Note that the implementation is /left-biased/ -- the elements of a
41 -- first argument are always preferred to the second, for example in
42 -- 'union' or 'insert'.
43 --
44 -- Operation comments contain the operation time complexity in
45 -- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>).
46 --
47 -- Be aware that the 'Functor', 'Traversable' and 'Data' instances
48 -- are the same as for the 'Data.Map.Lazy' module, so if they are used
49 -- on strict maps, the resulting maps will be lazy.
50 -----------------------------------------------------------------------------
51
52 -- See the notes at the beginning of Data.Map.Base.
53
54 module Data.Map.Strict
55 (
56 -- * Strictness properties
57 -- $strictness
58
59 -- * Map type
60 #if !defined(TESTING)
61 Map -- instance Eq,Show,Read
62 #else
63 Map(..) -- instance Eq,Show,Read
64 #endif
65
66 -- * Operators
67 , (!), (\\)
68
69 -- * Query
70 , null
71 , size
72 , member
73 , notMember
74 , lookup
75 , findWithDefault
76 , lookupLT
77 , lookupGT
78 , lookupLE
79 , lookupGE
80
81 -- * Construction
82 , empty
83 , singleton
84
85 -- ** Insertion
86 , insert
87 , insertWith
88 , insertWithKey
89 , insertLookupWithKey
90
91 -- ** Delete\/Update
92 , delete
93 , adjust
94 , adjustWithKey
95 , update
96 , updateWithKey
97 , updateLookupWithKey
98 , alter
99
100 -- * Combine
101
102 -- ** Union
103 , union
104 , unionWith
105 , unionWithKey
106 , unions
107 , unionsWith
108
109 -- ** Difference
110 , difference
111 , differenceWith
112 , differenceWithKey
113
114 -- ** Intersection
115 , intersection
116 , intersectionWith
117 , intersectionWithKey
118
119 -- ** Universal combining function
120 , mergeWithKey
121
122 -- * Traversal
123 -- ** Map
124 , map
125 , mapWithKey
126 , traverseWithKey
127 , mapAccum
128 , mapAccumWithKey
129 , mapAccumRWithKey
130 , mapKeys
131 , mapKeysWith
132 , mapKeysMonotonic
133
134 -- * Folds
135 , foldr
136 , foldl
137 , foldrWithKey
138 , foldlWithKey
139 -- ** Strict folds
140 , foldr'
141 , foldl'
142 , foldrWithKey'
143 , foldlWithKey'
144
145 -- * Conversion
146 , elems
147 , keys
148 , assocs
149 , keysSet
150 , fromSet
151
152 -- ** Lists
153 , toList
154 , fromList
155 , fromListWith
156 , fromListWithKey
157
158 -- ** Ordered lists
159 , toAscList
160 , toDescList
161 , fromAscList
162 , fromAscListWith
163 , fromAscListWithKey
164 , fromDistinctAscList
165
166 -- * Filter
167 , filter
168 , filterWithKey
169 , partition
170 , partitionWithKey
171
172 , mapMaybe
173 , mapMaybeWithKey
174 , mapEither
175 , mapEitherWithKey
176
177 , split
178 , splitLookup
179
180 -- * Submap
181 , isSubmapOf, isSubmapOfBy
182 , isProperSubmapOf, isProperSubmapOfBy
183
184 -- * Indexed
185 , lookupIndex
186 , findIndex
187 , elemAt
188 , updateAt
189 , deleteAt
190
191 -- * Min\/Max
192 , findMin
193 , findMax
194 , deleteMin
195 , deleteMax
196 , deleteFindMin
197 , deleteFindMax
198 , updateMin
199 , updateMax
200 , updateMinWithKey
201 , updateMaxWithKey
202 , minView
203 , maxView
204 , minViewWithKey
205 , maxViewWithKey
206
207 -- * Debugging
208 , showTree
209 , showTreeWith
210 , valid
211
212 #if defined(TESTING)
213 -- * Internals
214 , bin
215 , balanced
216 , join
217 , merge
218 #endif
219 ) where
220
221 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
222
223 import Data.Map.Base hiding
224 ( findWithDefault
225 , singleton
226 , insert
227 , insertWith
228 , insertWithKey
229 , insertLookupWithKey
230 , adjust
231 , adjustWithKey
232 , update
233 , updateWithKey
234 , updateLookupWithKey
235 , alter
236 , unionWith
237 , unionWithKey
238 , unionsWith
239 , differenceWith
240 , differenceWithKey
241 , intersectionWith
242 , intersectionWithKey
243 , mergeWithKey
244 , map
245 , mapWithKey
246 , mapAccum
247 , mapAccumWithKey
248 , mapAccumRWithKey
249 , mapKeysWith
250 , fromSet
251 , fromList
252 , fromListWith
253 , fromListWithKey
254 , fromAscList
255 , fromAscListWith
256 , fromAscListWithKey
257 , fromDistinctAscList
258 , mapMaybe
259 , mapMaybeWithKey
260 , mapEither
261 , mapEitherWithKey
262 , updateAt
263 , updateMin
264 , updateMax
265 , updateMinWithKey
266 , updateMaxWithKey
267 )
268 import qualified Data.Set.Base as Set
269 import Data.StrictPair
270
271 -- Use macros to define strictness of functions. STRICT_x_OF_y
272 -- denotes an y-ary function strict in the x-th parameter. Similarly
273 -- STRICT_x_y_OF_z denotes an z-ary function strict in the x-th and
274 -- y-th parameter. We do not use BangPatterns, because they are not
275 -- in any standard and we want the compilers to be compiled by as many
276 -- compilers as possible.
277 #define STRICT_2_OF_3(fn) fn _ arg _ | arg `seq` False = undefined
278 #define STRICT_1_2_OF_3(fn) fn arg1 arg2 _ | arg1 `seq` arg2 `seq` False = undefined
279 #define STRICT_2_3_OF_4(fn) fn _ arg1 arg2 _ | arg1 `seq` arg2 `seq` False = undefined
280
281 -- $strictness
282 --
283 -- This module satisfies the following strictness properties:
284 --
285 -- 1. Key and value arguments are evaluated to WHNF;
286 --
287 -- 2. Keys and values are evaluated to WHNF before they are stored in
288 -- the map.
289 --
290 -- Here are some examples that illustrate the first property:
291 --
292 -- > insertWith (\ new old -> old) k undefined m == undefined
293 -- > delete undefined m == undefined
294 --
295 -- Here are some examples that illustrate the second property:
296 --
297 -- > map (\ v -> undefined) m == undefined -- m is not empty
298 -- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
299
300 {--------------------------------------------------------------------
301 Query
302 --------------------------------------------------------------------}
303
304 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
305 -- the value at key @k@ or returns default value @def@
306 -- when the key is not in the map.
307 --
308 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
309 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
310
311 -- See Map.Base.Note: Local 'go' functions and capturing
312 findWithDefault :: Ord k => a -> k -> Map k a -> a
313 findWithDefault def k = def `seq` k `seq` go
314 where
315 go Tip = def
316 go (Bin _ kx x l r) = case compare k kx of
317 LT -> go l
318 GT -> go r
319 EQ -> x
320 #if __GLASGOW_HASKELL__ >= 700
321 {-# INLINABLE findWithDefault #-}
322 #else
323 {-# INLINE findWithDefault #-}
324 #endif
325
326 {--------------------------------------------------------------------
327 Construction
328 --------------------------------------------------------------------}
329
330 -- | /O(1)/. A map with a single element.
331 --
332 -- > singleton 1 'a' == fromList [(1, 'a')]
333 -- > size (singleton 1 'a') == 1
334
335 singleton :: k -> a -> Map k a
336 singleton k x = x `seq` Bin 1 k x Tip Tip
337 {-# INLINE singleton #-}
338
339 {--------------------------------------------------------------------
340 Insertion
341 --------------------------------------------------------------------}
342 -- | /O(log n)/. Insert a new key and value in the map.
343 -- If the key is already present in the map, the associated value is
344 -- replaced with the supplied value. 'insert' is equivalent to
345 -- @'insertWith' 'const'@.
346 --
347 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
348 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
349 -- > insert 5 'x' empty == singleton 5 'x'
350
351 -- See Map.Base.Note: Type of local 'go' function
352 insert :: Ord k => k -> a -> Map k a -> Map k a
353 insert = go
354 where
355 go :: Ord k => k -> a -> Map k a -> Map k a
356 STRICT_1_2_OF_3(go)
357 go kx x Tip = singleton kx x
358 go kx x (Bin sz ky y l r) =
359 case compare kx ky of
360 LT -> balanceL ky y (go kx x l) r
361 GT -> balanceR ky y l (go kx x r)
362 EQ -> Bin sz kx x l r
363 #if __GLASGOW_HASKELL__ >= 700
364 {-# INLINABLE insert #-}
365 #else
366 {-# INLINE insert #-}
367 #endif
368
369 -- | /O(log n)/. Insert with a function, combining new value and old value.
370 -- @'insertWith' f key value mp@
371 -- will insert the pair (key, value) into @mp@ if key does
372 -- not exist in the map. If the key does exist, the function will
373 -- insert the pair @(key, f new_value old_value)@.
374 --
375 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
376 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
377 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
378
379 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
380 insertWith f = insertWithKey (\_ x' y' -> f x' y')
381 #if __GLASGOW_HASKELL__ >= 700
382 {-# INLINABLE insertWith #-}
383 #else
384 {-# INLINE insertWith #-}
385 #endif
386
387 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
388 -- @'insertWithKey' f key value mp@
389 -- will insert the pair (key, value) into @mp@ if key does
390 -- not exist in the map. If the key does exist, the function will
391 -- insert the pair @(key,f key new_value old_value)@.
392 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
393 --
394 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
395 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
396 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
397 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
398
399 -- See Map.Base.Note: Type of local 'go' function
400 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
401 insertWithKey = go
402 where
403 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
404 STRICT_2_3_OF_4(go)
405 go _ kx x Tip = singleton kx x
406 go f kx x (Bin sy ky y l r) =
407 case compare kx ky of
408 LT -> balanceL ky y (go f kx x l) r
409 GT -> balanceR ky y l (go f kx x r)
410 EQ -> let x' = f kx x y
411 in x' `seq` Bin sy kx x' l r
412 #if __GLASGOW_HASKELL__ >= 700
413 {-# INLINABLE insertWithKey #-}
414 #else
415 {-# INLINE insertWithKey #-}
416 #endif
417
418 -- | /O(log n)/. Combines insert operation with old value retrieval.
419 -- The expression (@'insertLookupWithKey' f k x map@)
420 -- is a pair where the first element is equal to (@'lookup' k map@)
421 -- and the second element equal to (@'insertWithKey' f k x map@).
422 --
423 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
424 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
425 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
426 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
427 --
428 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
429 --
430 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
431 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
432 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
433
434 -- See Map.Base.Note: Type of local 'go' function
435 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
436 -> (Maybe a, Map k a)
437 insertLookupWithKey = go
438 where
439 go :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a, Map k a)
440 STRICT_2_3_OF_4(go)
441 go _ kx x Tip = Nothing `strictPair` singleton kx x
442 go f kx x (Bin sy ky y l r) =
443 case compare kx ky of
444 LT -> let (found, l') = go f kx x l
445 in found `strictPair` balanceL ky y l' r
446 GT -> let (found, r') = go f kx x r
447 in found `strictPair` balanceR ky y l r'
448 EQ -> let x' = f kx x y
449 in x' `seq` (Just y `strictPair` Bin sy kx x' l r)
450 #if __GLASGOW_HASKELL__ >= 700
451 {-# INLINABLE insertLookupWithKey #-}
452 #else
453 {-# INLINE insertLookupWithKey #-}
454 #endif
455
456 {--------------------------------------------------------------------
457 Deletion
458 --------------------------------------------------------------------}
459
460 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
461 -- When the key is not
462 -- a member of the map, the original map is returned.
463 --
464 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
465 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
466 -- > adjust ("new " ++) 7 empty == empty
467
468 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
469 adjust f = adjustWithKey (\_ x -> f x)
470 #if __GLASGOW_HASKELL__ >= 700
471 {-# INLINABLE adjust #-}
472 #else
473 {-# INLINE adjust #-}
474 #endif
475
476 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
477 -- a member of the map, the original map is returned.
478 --
479 -- > let f key x = (show key) ++ ":new " ++ x
480 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
481 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
482 -- > adjustWithKey f 7 empty == empty
483
484 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
485 adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
486 #if __GLASGOW_HASKELL__ >= 700
487 {-# INLINABLE adjustWithKey #-}
488 #else
489 {-# INLINE adjustWithKey #-}
490 #endif
491
492 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
493 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
494 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
495 --
496 -- > let f x = if x == "a" then Just "new a" else Nothing
497 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
498 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
499 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
500
501 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
502 update f = updateWithKey (\_ x -> f x)
503 #if __GLASGOW_HASKELL__ >= 700
504 {-# INLINABLE update #-}
505 #else
506 {-# INLINE update #-}
507 #endif
508
509 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
510 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
511 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
512 -- to the new value @y@.
513 --
514 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
515 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
516 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
517 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
518
519 -- See Map.Base.Note: Type of local 'go' function
520 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
521 updateWithKey = go
522 where
523 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
524 STRICT_2_OF_3(go)
525 go _ _ Tip = Tip
526 go f k(Bin sx kx x l r) =
527 case compare k kx of
528 LT -> balanceR kx x (go f k l) r
529 GT -> balanceL kx x l (go f k r)
530 EQ -> case f kx x of
531 Just x' -> x' `seq` Bin sx kx x' l r
532 Nothing -> glue l r
533 #if __GLASGOW_HASKELL__ >= 700
534 {-# INLINABLE updateWithKey #-}
535 #else
536 {-# INLINE updateWithKey #-}
537 #endif
538
539 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
540 -- The function returns changed value, if it is updated.
541 -- Returns the original key value if the map entry is deleted.
542 --
543 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
544 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
545 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
546 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
547
548 -- See Map.Base.Note: Type of local 'go' function
549 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
550 updateLookupWithKey = go
551 where
552 go :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
553 STRICT_2_OF_3(go)
554 go _ _ Tip = (Nothing,Tip)
555 go f k (Bin sx kx x l r) =
556 case compare k kx of
557 LT -> let (found,l') = go f k l
558 in found `strictPair` balanceR kx x l' r
559 GT -> let (found,r') = go f k r
560 in found `strictPair` balanceL kx x l r'
561 EQ -> case f kx x of
562 Just x' -> x' `seq` (Just x' `strictPair` Bin sx kx x' l r)
563 Nothing -> (Just x,glue l r)
564 #if __GLASGOW_HASKELL__ >= 700
565 {-# INLINABLE updateLookupWithKey #-}
566 #else
567 {-# INLINE updateLookupWithKey #-}
568 #endif
569
570 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
571 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
572 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
573 --
574 -- > let f _ = Nothing
575 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
576 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
577 -- >
578 -- > let f _ = Just "c"
579 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
580 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
581
582 -- See Map.Base.Note: Type of local 'go' function
583 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
584 alter = go
585 where
586 go :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
587 STRICT_2_OF_3(go)
588 go f k Tip = case f Nothing of
589 Nothing -> Tip
590 Just x -> singleton k x
591
592 go f k (Bin sx kx x l r) = case compare k kx of
593 LT -> balance kx x (go f k l) r
594 GT -> balance kx x l (go f k r)
595 EQ -> case f (Just x) of
596 Just x' -> x' `seq` Bin sx kx x' l r
597 Nothing -> glue l r
598 #if __GLASGOW_HASKELL__ >= 700
599 {-# INLINABLE alter #-}
600 #else
601 {-# INLINE alter #-}
602 #endif
603
604 {--------------------------------------------------------------------
605 Indexing
606 --------------------------------------------------------------------}
607
608 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
609 -- invalid index is used.
610 --
611 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
612 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
613 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
614 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
615 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
616 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
617 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
618 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
619
620 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
621 updateAt f i t = i `seq`
622 case t of
623 Tip -> error "Map.updateAt: index out of range"
624 Bin sx kx x l r -> case compare i sizeL of
625 LT -> balanceR kx x (updateAt f i l) r
626 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
627 EQ -> case f kx x of
628 Just x' -> x' `seq` Bin sx kx x' l r
629 Nothing -> glue l r
630 where
631 sizeL = size l
632
633 {--------------------------------------------------------------------
634 Minimal, Maximal
635 --------------------------------------------------------------------}
636
637 -- | /O(log n)/. Update the value at the minimal key.
638 --
639 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
640 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
641
642 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
643 updateMin f m
644 = updateMinWithKey (\_ x -> f x) m
645
646 -- | /O(log n)/. Update the value at the maximal key.
647 --
648 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
649 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
650
651 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
652 updateMax f m
653 = updateMaxWithKey (\_ x -> f x) m
654
655
656 -- | /O(log n)/. Update the value at the minimal key.
657 --
658 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
659 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
660
661 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
662 updateMinWithKey _ Tip = Tip
663 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
664 Nothing -> r
665 Just x' -> x' `seq` Bin sx kx x' Tip r
666 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
667
668 -- | /O(log n)/. Update the value at the maximal key.
669 --
670 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
671 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
672
673 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
674 updateMaxWithKey _ Tip = Tip
675 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
676 Nothing -> l
677 Just x' -> x' `seq` Bin sx kx x' l Tip
678 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
679
680 {--------------------------------------------------------------------
681 Union.
682 --------------------------------------------------------------------}
683
684 -- | The union of a list of maps, with a combining operation:
685 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
686 --
687 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
688 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
689
690 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
691 unionsWith f ts
692 = foldlStrict (unionWith f) empty ts
693 #if __GLASGOW_HASKELL__ >= 700
694 {-# INLINABLE unionsWith #-}
695 #endif
696
697 {--------------------------------------------------------------------
698 Union with a combining function
699 --------------------------------------------------------------------}
700 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
701 --
702 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
703
704 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
705 unionWith f m1 m2
706 = unionWithKey (\_ x y -> f x y) m1 m2
707 #if __GLASGOW_HASKELL__ >= 700
708 {-# INLINABLE unionWith #-}
709 #endif
710
711 -- | /O(n+m)/.
712 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
713 -- Hedge-union is more efficient on (bigset \``union`\` smallset).
714 --
715 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
716 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
717
718 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
719 unionWithKey _ Tip t2 = t2
720 unionWithKey _ t1 Tip = t1
721 unionWithKey f t1 t2 = hedgeUnionWithKey f NothingS NothingS t1 t2
722 #if __GLASGOW_HASKELL__ >= 700
723 {-# INLINABLE unionWithKey #-}
724 #endif
725
726 hedgeUnionWithKey :: Ord a
727 => (a -> b -> b -> b)
728 -> MaybeS a -> MaybeS a
729 -> Map a b -> Map a b
730 -> Map a b
731 hedgeUnionWithKey _ _ _ t1 Tip
732 = t1
733 hedgeUnionWithKey _ blo bhi Tip (Bin _ kx x l r)
734 = join kx x (filterGt blo l) (filterLt bhi r)
735 hedgeUnionWithKey f blo bhi (Bin _ kx x l r) t2
736 = newx `seq` join kx newx (hedgeUnionWithKey f blo bmi l lt)
737 (hedgeUnionWithKey f bmi bhi r gt)
738 where
739 bmi = JustS kx
740 lt = trim blo bmi t2
741 (found,gt) = trimLookupLo kx bhi t2
742 newx = case found of
743 Nothing -> x
744 Just (_,y) -> f kx x y
745 #if __GLASGOW_HASKELL__ >= 700
746 {-# INLINABLE hedgeUnionWithKey #-}
747 #endif
748
749 {--------------------------------------------------------------------
750 Difference
751 --------------------------------------------------------------------}
752
753 -- | /O(n+m)/. Difference with a combining function.
754 -- When two equal keys are
755 -- encountered, the combining function is applied to the values of these keys.
756 -- If it returns 'Nothing', the element is discarded (proper set difference). If
757 -- it returns (@'Just' y@), the element is updated with a new value @y@.
758 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
759 --
760 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
761 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
762 -- > == singleton 3 "b:B"
763
764 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
765 differenceWith f m1 m2
766 = differenceWithKey (\_ x y -> f x y) m1 m2
767 #if __GLASGOW_HASKELL__ >= 700
768 {-# INLINABLE differenceWith #-}
769 #endif
770
771 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
772 -- encountered, the combining function is applied to the key and both values.
773 -- If it returns 'Nothing', the element is discarded (proper set difference). If
774 -- it returns (@'Just' y@), the element is updated with a new value @y@.
775 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
776 --
777 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
778 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
779 -- > == singleton 3 "3:b|B"
780
781 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
782 differenceWithKey _ Tip _ = Tip
783 differenceWithKey _ t1 Tip = t1
784 differenceWithKey f t1 t2 = hedgeDiffWithKey f NothingS NothingS t1 t2
785 #if __GLASGOW_HASKELL__ >= 700
786 {-# INLINABLE differenceWithKey #-}
787 #endif
788
789 hedgeDiffWithKey :: Ord a
790 => (a -> b -> c -> Maybe b)
791 -> MaybeS a -> MaybeS a
792 -> Map a b -> Map a c
793 -> Map a b
794 hedgeDiffWithKey _ _ _ Tip _
795 = Tip
796 hedgeDiffWithKey _ blo bhi (Bin _ kx x l r) Tip
797 = join kx x (filterGt blo l) (filterLt bhi r)
798 hedgeDiffWithKey f blo bhi t (Bin _ kx x l r)
799 = case found of
800 Nothing -> merge tl tr
801 Just (ky,y) ->
802 case f ky y x of
803 Nothing -> merge tl tr
804 Just z -> z `seq` join ky z tl tr
805 where
806 bmi = JustS kx
807 lt = trim blo bmi t
808 (found,gt) = trimLookupLo kx bhi t
809 tl = hedgeDiffWithKey f blo bmi lt l
810 tr = hedgeDiffWithKey f bmi bhi gt r
811 #if __GLASGOW_HASKELL__ >= 700
812 {-# INLINABLE hedgeDiffWithKey #-}
813 #endif
814
815 {--------------------------------------------------------------------
816 Intersection
817 --------------------------------------------------------------------}
818
819 -- | /O(n+m)/. Intersection with a combining function.
820 --
821 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
822
823 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
824 intersectionWith f m1 m2
825 = intersectionWithKey (\_ x y -> f x y) m1 m2
826 #if __GLASGOW_HASKELL__ >= 700
827 {-# INLINABLE intersectionWith #-}
828 #endif
829
830 -- | /O(n+m)/. Intersection with a combining function.
831 -- Intersection is more efficient on (bigset \``intersection`\` smallset).
832 --
833 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
834 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
835
836
837 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
838 intersectionWithKey _ Tip _ = Tip
839 intersectionWithKey _ _ Tip = Tip
840 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
841 if s1 >= s2 then
842 case splitLookupWithKey k2 t1 of
843 (lt, Just (k, x), gt) -> case f k x x2 of x' -> x' `seq` join k x' (intersectionWithKey f lt l2) (intersectionWithKey f gt r2)
844 (lt, Nothing, gt) -> merge (intersectionWithKey f lt l2) (intersectionWithKey f gt r2)
845 else
846 case splitLookup k1 t2 of
847 (lt, Just x, gt) -> case f k1 x1 x of x' -> x' `seq` join k1 x' (intersectionWithKey f l1 lt) (intersectionWithKey f r1 gt)
848 (lt, Nothing, gt) -> merge (intersectionWithKey f l1 lt) (intersectionWithKey f r1 gt)
849 #if __GLASGOW_HASKELL__ >= 700
850 {-# INLINABLE intersectionWithKey #-}
851 #endif
852
853
854 {--------------------------------------------------------------------
855 MergeWithKey
856 --------------------------------------------------------------------}
857
858 -- | /O(n+m)/. A high-performance universal combining function. This function
859 -- is used to define 'unionWith', 'unionWithKey', 'differenceWith',
860 -- 'differenceWithKey', 'intersectionWith', 'intersectionWithKey' and can be
861 -- used to define other custom combine functions.
862 --
863 -- Please make sure you know what is going on when using 'mergeWithKey',
864 -- otherwise you can be surprised by unexpected code growth or even
865 -- corruption of the data structure.
866 --
867 -- When 'mergeWithKey' is given three arguments, it is inlined to the call
868 -- site. You should therefore use 'mergeWithKey' only to define your custom
869 -- combining functions. For example, you could define 'unionWithKey',
870 -- 'differenceWithKey' and 'intersectionWithKey' as
871 --
872 -- > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
873 -- > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const empty) m1 m2
874 -- > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const empty) (const empty) m1 m2
875 --
876 -- When calling @'mergeWithKey' combine only1 only2@, a function combining two
877 -- 'IntMap's is created, such that
878 --
879 -- * if a key is present in both maps, it is passed with both corresponding
880 -- values to the @combine@ function. Depending on the result, the key is either
881 -- present in the result with specified value, or is left out;
882 --
883 -- * a nonempty subtree present only in the first map is passed to @only1@ and
884 -- the output is added to the result;
885 --
886 -- * a nonempty subtree present only in the second map is passed to @only2@ and
887 -- the output is added to the result.
888 --
889 -- The @only1@ and @only2@ methods /must return a map with a subset (possibly empty) of the keys of the given map/.
890 -- The values can be modified arbitrarily. Most common variants of @only1@ and
891 -- @only2@ are 'id' and @'const' 'empty'@, but for example @'map' f@ or
892 -- @'filterWithKey' f@ could be used for any @f@.
893
894 mergeWithKey :: Ord k => (k -> a -> b -> Maybe c) -> (Map k a -> Map k c) -> (Map k b -> Map k c)
895 -> Map k a -> Map k b -> Map k c
896 mergeWithKey f g1 g2 = go
897 where
898 go Tip t2 = g2 t2
899 go t1 Tip = g1 t1
900 go t1 t2 = hedgeMerge NothingS NothingS t1 t2
901
902 hedgeMerge _ _ t1 Tip = g1 t1
903 hedgeMerge blo bhi Tip (Bin _ kx x l r) = g2 $ join kx x (filterGt blo l) (filterLt bhi r)
904 hedgeMerge blo bhi (Bin _ kx x l r) t2 = let l' = hedgeMerge blo bmi l (trim blo bmi t2)
905 (found, trim_t2) = trimLookupLo kx bhi t2
906 r' = hedgeMerge bmi bhi r trim_t2
907 in case found of
908 Nothing -> case g1 (singleton kx x) of
909 Tip -> merge l' r'
910 (Bin _ _ x' Tip Tip) -> join kx x' l' r'
911 _ -> error "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
912 Just x2 -> case f kx x x2 of
913 Nothing -> merge l' r'
914 Just x' -> x' `seq` join kx x' l' r'
915 where bmi = JustS kx
916 {-# INLINE mergeWithKey #-}
917
918 {--------------------------------------------------------------------
919 Filter and partition
920 --------------------------------------------------------------------}
921
922 -- | /O(n)/. Map values and collect the 'Just' results.
923 --
924 -- > let f x = if x == "a" then Just "new a" else Nothing
925 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
926
927 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
928 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
929
930 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
931 --
932 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
933 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
934
935 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
936 mapMaybeWithKey _ Tip = Tip
937 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
938 Just y -> y `seq` join kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
939 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
940
941 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
942 --
943 -- > let f a = if a < "c" then Left a else Right a
944 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
945 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
946 -- >
947 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
948 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
949
950 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
951 mapEither f m
952 = mapEitherWithKey (\_ x -> f x) m
953
954 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
955 --
956 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
957 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
958 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
959 -- >
960 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
961 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
962
963 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
964 mapEitherWithKey _ Tip = (Tip, Tip)
965 mapEitherWithKey f (Bin _ kx x l r) = case f kx x of
966 Left y -> y `seq` (join kx y l1 r1 `strictPair` merge l2 r2)
967 Right z -> z `seq` (merge l1 r1 `strictPair` join kx z l2 r2)
968 where
969 (l1,l2) = mapEitherWithKey f l
970 (r1,r2) = mapEitherWithKey f r
971
972 {--------------------------------------------------------------------
973 Mapping
974 --------------------------------------------------------------------}
975 -- | /O(n)/. Map a function over all values in the map.
976 --
977 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
978
979 map :: (a -> b) -> Map k a -> Map k b
980 map _ Tip = Tip
981 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)
982
983 -- | /O(n)/. Map a function over all values in the map.
984 --
985 -- > let f key x = (show key) ++ ":" ++ x
986 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
987
988 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
989 mapWithKey _ Tip = Tip
990 mapWithKey f (Bin sx kx x l r) = let x' = f kx x
991 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
992
993 -- | /O(n)/. The function 'mapAccum' threads an accumulating
994 -- argument through the map in ascending order of keys.
995 --
996 -- > let f a b = (a ++ b, b ++ "X")
997 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
998
999 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1000 mapAccum f a m
1001 = mapAccumWithKey (\a' _ x' -> f a' x') a m
1002
1003 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
1004 -- argument through the map in ascending order of keys.
1005 --
1006 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
1007 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
1008
1009 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1010 mapAccumWithKey f a t
1011 = mapAccumL f a t
1012
1013 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
1014 -- argument through the map in ascending order of keys.
1015 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1016 mapAccumL _ a Tip = (a,Tip)
1017 mapAccumL f a (Bin sx kx x l r) =
1018 let (a1,l') = mapAccumL f a l
1019 (a2,x') = f a1 kx x
1020 (a3,r') = mapAccumL f a2 r
1021 in x' `seq` (a3,Bin sx kx x' l' r')
1022
1023 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
1024 -- argument through the map in descending order of keys.
1025 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
1026 mapAccumRWithKey _ a Tip = (a,Tip)
1027 mapAccumRWithKey f a (Bin sx kx x l r) =
1028 let (a1,r') = mapAccumRWithKey f a r
1029 (a2,x') = f a1 kx x
1030 (a3,l') = mapAccumRWithKey f a2 l
1031 in x' `seq` (a3,Bin sx kx x' l' r')
1032
1033 -- | /O(n*log n)/.
1034 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1035 --
1036 -- The size of the result may be smaller if @f@ maps two or more distinct
1037 -- keys to the same new key. In this case the associated values will be
1038 -- combined using @c@.
1039 --
1040 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1041 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1042
1043 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1044 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
1045 #if __GLASGOW_HASKELL__ >= 700
1046 {-# INLINABLE mapKeysWith #-}
1047 #endif
1048
1049 {--------------------------------------------------------------------
1050 Conversions
1051 --------------------------------------------------------------------}
1052
1053 -- | /O(n)/. Build a map from a set of keys and a function which for each key
1054 -- computes its value.
1055 --
1056 -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
1057 -- > fromSet undefined Data.Set.empty == empty
1058
1059 fromSet :: (k -> a) -> Set.Set k -> Map k a
1060 fromSet _ Set.Tip = Tip
1061 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)
1062
1063 {--------------------------------------------------------------------
1064 Lists
1065 use [foldlStrict] to reduce demand on the control-stack
1066 --------------------------------------------------------------------}
1067 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1068 -- If the list contains more than one value for the same key, the last value
1069 -- for the key is retained.
1070 --
1071 -- > fromList [] == empty
1072 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1073 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1074
1075 fromList :: Ord k => [(k,a)] -> Map k a
1076 fromList xs
1077 = foldlStrict ins empty xs
1078 where
1079 ins t (k,x) = insert k x t
1080 #if __GLASGOW_HASKELL__ >= 700
1081 {-# INLINABLE fromList #-}
1082 #endif
1083
1084 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1085 --
1086 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1087 -- > fromListWith (++) [] == empty
1088
1089 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1090 fromListWith f xs
1091 = fromListWithKey (\_ x y -> f x y) xs
1092 #if __GLASGOW_HASKELL__ >= 700
1093 {-# INLINABLE fromListWith #-}
1094 #endif
1095
1096 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1097 --
1098 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1099 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1100 -- > fromListWithKey f [] == empty
1101
1102 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1103 fromListWithKey f xs
1104 = foldlStrict ins empty xs
1105 where
1106 ins t (k,x) = insertWithKey f k x t
1107 #if __GLASGOW_HASKELL__ >= 700
1108 {-# INLINABLE fromListWithKey #-}
1109 #endif
1110
1111 {--------------------------------------------------------------------
1112 Building trees from ascending/descending lists can be done in linear time.
1113
1114 Note that if [xs] is ascending that:
1115 fromAscList xs == fromList xs
1116 fromAscListWith f xs == fromListWith f xs
1117 --------------------------------------------------------------------}
1118 -- | /O(n)/. Build a map from an ascending list in linear time.
1119 -- /The precondition (input list is ascending) is not checked./
1120 --
1121 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1122 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1123 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1124 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1125
1126 fromAscList :: Eq k => [(k,a)] -> Map k a
1127 fromAscList xs
1128 = fromAscListWithKey (\_ x _ -> x) xs
1129 #if __GLASGOW_HASKELL__ >= 700
1130 {-# INLINABLE fromAscList #-}
1131 #endif
1132
1133 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1134 -- /The precondition (input list is ascending) is not checked./
1135 --
1136 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1137 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1138 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1139
1140 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1141 fromAscListWith f xs
1142 = fromAscListWithKey (\_ x y -> f x y) xs
1143 #if __GLASGOW_HASKELL__ >= 700
1144 {-# INLINABLE fromAscListWith #-}
1145 #endif
1146
1147 -- | /O(n)/. Build a map from an ascending list in linear time with a
1148 -- combining function for equal keys.
1149 -- /The precondition (input list is ascending) is not checked./
1150 --
1151 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1152 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1153 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1154 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1155
1156 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1157 fromAscListWithKey f xs
1158 = fromDistinctAscList (combineEq f xs)
1159 where
1160 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1161 combineEq _ xs'
1162 = case xs' of
1163 [] -> []
1164 [x] -> [x]
1165 (x:xx) -> combineEq' x xx
1166
1167 combineEq' z [] = [z]
1168 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1169 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1170 | otherwise = z:combineEq' x xs'
1171 #if __GLASGOW_HASKELL__ >= 700
1172 {-# INLINABLE fromAscListWithKey #-}
1173 #endif
1174
1175 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1176 -- /The precondition is not checked./
1177 --
1178 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1179 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1180 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1181
1182 fromDistinctAscList :: [(k,a)] -> Map k a
1183 fromDistinctAscList xs
1184 = create const (length xs) xs
1185 where
1186 -- 1) use continuations so that we use heap space instead of stack space.
1187 -- 2) special case for n==5 to create bushier trees.
1188 create c 0 xs' = c Tip xs'
1189 create c 5 xs' = case xs' of
1190 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1191 -> x1 `seq` x2 `seq` x3 `seq` x4 `seq` x5 `seq`
1192 c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3))
1193 (singleton k5 x5)) xx
1194 _ -> error "fromDistinctAscList create"
1195 create c n xs' = seq nr $ create (createR nr c) nl xs'
1196 where nl = n `div` 2
1197 nr = n - nl - 1
1198
1199 createR n c l ((k,x):ys) = x `seq` create (createB l k x c) n ys
1200 createR _ _ _ [] = error "fromDistinctAscList createR []"
1201 createB l k x c r zs = x `seq` c (bin k x l r) zs