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