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