More documentation tweaks
[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 is strict in keys and values. In particular,
271 --
272 -- * key and value arguments are evaluated to WHNF before the function
273 -- body is evaluated, and
274 --
275 -- * keys and values returned by higher-order function arguments are
276 -- evaluated to WHNF before they are inserted into the map.
277 --
278 -- Here are some examples:
279 --
280 -- > insertWith (+) k undefined m == undefined
281 -- > delete undefined m == undefined
282 -- > map (\ v -> undefined) == undefined
283 -- > mapKeys (\ k -> undefined) == undefined
284
285 {--------------------------------------------------------------------
286 Query
287 --------------------------------------------------------------------}
288
289 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
290 -- the value at key @k@ or returns default value @def@
291 -- when the key is not in the map.
292 --
293 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
294 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
295
296 findWithDefault :: Ord k => a -> k -> Map k a -> a
297 findWithDefault !def k m = case lookup k m of
298 Nothing -> def
299 Just x -> x
300 #if __GLASGOW_HASKELL__ >= 700
301 {-# INLINABLE findWithDefault #-}
302 #else
303 {-# INLINE findWithDefault #-}
304 #endif
305
306 {--------------------------------------------------------------------
307 Construction
308 --------------------------------------------------------------------}
309
310 -- | /O(1)/. A map with a single element.
311 --
312 -- > singleton 1 'a' == fromList [(1, 'a')]
313 -- > size (singleton 1 'a') == 1
314
315 singleton :: k -> a -> Map k a
316 singleton k !x = Bin 1 k x Tip Tip
317
318 {--------------------------------------------------------------------
319 Insertion
320 --------------------------------------------------------------------}
321 -- | /O(log n)/. Insert a new key and value in the map.
322 -- If the key is already present in the map, the associated value is
323 -- replaced with the supplied value. 'insert' is equivalent to
324 -- @'insertWith' 'const'@.
325 --
326 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
327 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
328 -- > insert 5 'x' empty == singleton 5 'x'
329
330 insert :: Ord k => k -> a -> Map k a -> Map k a
331 insert = go
332 where
333 go !kx !x Tip = singleton kx x
334 go kx x (Bin sz ky y l r) =
335 case compare kx ky of
336 LT -> balanceL ky y (go kx x l) r
337 GT -> balanceR ky y l (go kx x r)
338 EQ -> Bin sz kx x l r
339 #if __GLASGOW_HASKELL__ >= 700
340 {-# INLINEABLE insert #-}
341 #else
342 {-# INLINE insert #-}
343 #endif
344
345 -- | /O(log n)/. Insert with a function, combining new value and old value.
346 -- @'insertWith' f key value mp@
347 -- will insert the pair (key, value) into @mp@ if key does
348 -- not exist in the map. If the key does exist, the function will
349 -- insert the pair @(key, f new_value old_value)@.
350 --
351 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
352 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
353 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
354
355 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
356 insertWith f = insertWithKey (\_ x' y' -> f x' y')
357 {-# INLINE insertWith #-}
358
359 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
360 -- @'insertWithKey' f key value mp@
361 -- will insert the pair (key, value) into @mp@ if key does
362 -- not exist in the map. If the key does exist, the function will
363 -- insert the pair @(key,f key new_value old_value)@.
364 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
365 --
366 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
367 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
368 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
369 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
370
371 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
372 insertWithKey = go
373 where
374 go _ !kx !x Tip = singleton kx x
375 go f kx x (Bin sy ky y l r) =
376 case compare kx ky of
377 LT -> balanceL ky y (go f kx x l) r
378 GT -> balanceR ky y l (go f kx x r)
379 EQ -> let !x' = f kx x y
380 in Bin sy kx x' l r
381 #if __GLASGOW_HASKELL__ >= 700
382 {-# INLINEABLE insertWithKey #-}
383 #else
384 {-# INLINE insertWithKey #-}
385 #endif
386
387 -- | /O(log n)/. Combines insert operation with old value retrieval.
388 -- The expression (@'insertLookupWithKey' f k x map@)
389 -- is a pair where the first element is equal to (@'lookup' k map@)
390 -- and the second element equal to (@'insertWithKey' f k x map@).
391 --
392 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
393 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
394 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
395 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
396 --
397 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
398 --
399 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
400 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
401 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
402
403 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
404 -> (Maybe a, Map k a)
405 insertLookupWithKey = go
406 where
407 go _ !kx !x Tip = (Nothing, singleton kx x)
408 go f kx x (Bin sy ky y l r) =
409 case compare kx ky of
410 LT -> let (found, l') = go f kx x l
411 !t = balanceL ky y l' r
412 in (found, t)
413 GT -> let (found, r') = go f kx x r
414 !t = balanceR ky y l r'
415 in (found, t)
416 EQ -> let !x' = f kx x y
417 !t = Bin sy kx x' l r
418 in (Just y, t)
419 #if __GLASGOW_HASKELL__ >= 700
420 {-# INLINEABLE insertLookupWithKey #-}
421 #else
422 {-# INLINE insertLookupWithKey #-}
423 #endif
424
425 {--------------------------------------------------------------------
426 Deletion
427 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
428 --------------------------------------------------------------------}
429
430 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
431 -- When the key is not
432 -- a member of the map, the original map is returned.
433 --
434 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
435 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
436 -- > adjust ("new " ++) 7 empty == empty
437
438 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
439 adjust f = adjustWithKey (\_ x -> f x)
440 {-# INLINE adjust #-}
441
442 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
443 -- a member of the map, the original map is returned.
444 --
445 -- > let f key x = (show key) ++ ":new " ++ x
446 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
447 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
448 -- > adjustWithKey f 7 empty == empty
449
450 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
451 adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
452 {-# INLINE adjustWithKey #-}
453
454 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
455 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
456 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
457 --
458 -- > let f x = if x == "a" then Just "new a" else Nothing
459 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
460 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
461 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
462
463 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
464 update f = updateWithKey (\_ x -> f x)
465 {-# INLINE update #-}
466
467 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
468 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
469 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
470 -- to the new value @y@.
471 --
472 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
473 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
474 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
475 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
476
477 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
478 updateWithKey = go
479 where
480 go _ !_ Tip = Tip
481 go f k(Bin sx kx x l r) =
482 case compare k kx of
483 LT -> balanceR kx x (go f k l) r
484 GT -> balanceL kx x l (go f k r)
485 EQ -> case f kx x of
486 Just !x' -> Bin sx kx x' l r
487 Nothing -> glue l r
488 #if __GLASGOW_HASKELL__ >= 700
489 {-# INLINEABLE updateWithKey #-}
490 #else
491 {-# INLINE updateWithKey #-}
492 #endif
493
494 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
495 -- The function returns changed value, if it is updated.
496 -- Returns the original key value if the map entry is deleted.
497 --
498 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
499 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
500 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
501 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
502
503 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
504 updateLookupWithKey = go
505 where
506 go _ !_ Tip = (Nothing,Tip)
507 go f k (Bin sx kx x l r) =
508 case compare k kx of
509 LT -> let (found,l') = go f k l
510 !t = balanceR kx x l' r
511 in (found,t)
512 GT -> let (found,r') = go f k r
513 !t = balanceL kx x l r'
514 in (found,t)
515 EQ -> case f kx x of
516 Just !x' -> let !t = Bin sx kx x' l r
517 in (Just x',t)
518 Nothing -> (Just x,glue l r)
519 #if __GLASGOW_HASKELL__ >= 700
520 {-# INLINEABLE updateLookupWithKey #-}
521 #else
522 {-# INLINE updateLookupWithKey #-}
523 #endif
524
525 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
526 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
527 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
528 --
529 -- > let f _ = Nothing
530 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
531 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
532 -- >
533 -- > let f _ = Just "c"
534 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
535 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
536
537 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
538 alter = go
539 where
540 go f !k Tip = case f Nothing of
541 Nothing -> Tip
542 Just x -> singleton k x
543
544 go f k (Bin sx kx x l r) = case compare k kx of
545 LT -> balance kx x (go f k l) r
546 GT -> balance kx x l (go f k r)
547 EQ -> case f (Just x) of
548 Just !x' -> Bin sx kx x' l r
549 Nothing -> glue l r
550 #if __GLASGOW_HASKELL__ >= 700
551 {-# INLINEABLE alter #-}
552 #else
553 {-# INLINE alter #-}
554 #endif
555
556 {--------------------------------------------------------------------
557 Indexing
558 --------------------------------------------------------------------}
559
560 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
561 -- invalid index is used.
562 --
563 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
564 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
565 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
566 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
567 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
568 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
569 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
570 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
571
572 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
573 updateAt f i t = i `seq`
574 case t of
575 Tip -> error "Map.updateAt: index out of range"
576 Bin sx kx x l r -> case compare i sizeL of
577 LT -> balanceR kx x (updateAt f i l) r
578 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
579 EQ -> case f kx x of
580 Just !x' -> Bin sx kx x' l r
581 Nothing -> glue l r
582 where
583 sizeL = size l
584 #if __GLASGOW_HASKELL__ >= 700
585 {-# INLINABLE updateAt #-}
586 #endif
587
588 {--------------------------------------------------------------------
589 Minimal, Maximal
590 --------------------------------------------------------------------}
591
592 -- | /O(log n)/. Update the value at the minimal key.
593 --
594 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
595 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
596
597 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
598 updateMin f m
599 = updateMinWithKey (\_ x -> f x) m
600 #if __GLASGOW_HASKELL__ >= 700
601 {-# INLINABLE updateMin #-}
602 #endif
603
604 -- | /O(log n)/. Update the value at the maximal key.
605 --
606 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
607 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
608
609 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
610 updateMax f m
611 = updateMaxWithKey (\_ x -> f x) m
612 #if __GLASGOW_HASKELL__ >= 700
613 {-# INLINABLE updateMax #-}
614 #endif
615
616
617 -- | /O(log n)/. Update the value at the minimal key.
618 --
619 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
620 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
621
622 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
623 updateMinWithKey _ Tip = Tip
624 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
625 Nothing -> r
626 Just !x' -> Bin sx kx x' Tip r
627 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
628 #if __GLASGOW_HASKELL__ >= 700
629 {-# INLINABLE updateMinWithKey #-}
630 #endif
631
632 -- | /O(log n)/. Update the value at the maximal key.
633 --
634 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
635 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
636
637 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
638 updateMaxWithKey _ Tip = Tip
639 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
640 Nothing -> l
641 Just !x' -> Bin sx kx x' l Tip
642 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
643 #if __GLASGOW_HASKELL__ >= 700
644 {-# INLINABLE updateMaxWithKey #-}
645 #endif
646
647 {--------------------------------------------------------------------
648 Union.
649 --------------------------------------------------------------------}
650
651 -- | The union of a list of maps, with a combining operation:
652 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
653 --
654 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
655 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
656
657 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
658 unionsWith f ts
659 = foldlStrict (unionWith f) empty ts
660 #if __GLASGOW_HASKELL__ >= 700
661 {-# INLINABLE unionsWith #-}
662 #endif
663
664 {--------------------------------------------------------------------
665 Union with a combining function
666 --------------------------------------------------------------------}
667 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
668 --
669 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
670
671 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
672 unionWith f m1 m2
673 = unionWithKey (\_ x y -> f x y) m1 m2
674 {-# INLINE unionWith #-}
675
676 -- | /O(n+m)/.
677 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
678 -- Hedge-union is more efficient on (bigset \``union`\` smallset).
679 --
680 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
681 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
682
683 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
684 unionWithKey _ Tip t2 = t2
685 unionWithKey _ t1 Tip = t1
686 unionWithKey f t1 t2 = hedgeUnionWithKey f NothingS NothingS t1 t2
687 #if __GLASGOW_HASKELL__ >= 700
688 {-# INLINABLE unionWithKey #-}
689 #endif
690
691 hedgeUnionWithKey :: Ord a
692 => (a -> b -> b -> b)
693 -> MaybeS a -> MaybeS a
694 -> Map a b -> Map a b
695 -> Map a b
696 hedgeUnionWithKey _ _ _ t1 Tip
697 = t1
698 hedgeUnionWithKey _ blo bhi Tip (Bin _ kx x l r)
699 = join kx x (filterGt blo l) (filterLt bhi r)
700 hedgeUnionWithKey f blo bhi (Bin _ kx x l r) t2
701 = newx `seq` join kx newx (hedgeUnionWithKey f blo bmi l lt)
702 (hedgeUnionWithKey f bmi bhi r gt)
703 where
704 bmi = JustS kx
705 lt = trim blo bmi t2
706 (found,gt) = trimLookupLo kx bhi t2
707 newx = case found of
708 Nothing -> x
709 Just (_,y) -> f kx x y
710 #if __GLASGOW_HASKELL__ >= 700
711 {-# INLINABLE hedgeUnionWithKey #-}
712 #endif
713
714 {--------------------------------------------------------------------
715 Difference
716 --------------------------------------------------------------------}
717
718 -- | /O(n+m)/. Difference with a combining function.
719 -- When two equal keys are
720 -- encountered, the combining function is applied to the values of these keys.
721 -- If it returns 'Nothing', the element is discarded (proper set difference). If
722 -- it returns (@'Just' y@), the element is updated with a new value @y@.
723 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
724 --
725 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
726 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
727 -- > == singleton 3 "b:B"
728
729 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
730 differenceWith f m1 m2
731 = differenceWithKey (\_ x y -> f x y) m1 m2
732 {-# INLINE differenceWith #-}
733
734 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
735 -- encountered, the combining function is applied to the key and both values.
736 -- If it returns 'Nothing', the element is discarded (proper set difference). If
737 -- it returns (@'Just' y@), the element is updated with a new value @y@.
738 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
739 --
740 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
741 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
742 -- > == singleton 3 "3:b|B"
743
744 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
745 differenceWithKey _ Tip _ = Tip
746 differenceWithKey _ t1 Tip = t1
747 differenceWithKey f t1 t2 = hedgeDiffWithKey f NothingS NothingS t1 t2
748 #if __GLASGOW_HASKELL__ >= 700
749 {-# INLINABLE differenceWithKey #-}
750 #endif
751
752 hedgeDiffWithKey :: Ord a
753 => (a -> b -> c -> Maybe b)
754 -> MaybeS a -> MaybeS a
755 -> Map a b -> Map a c
756 -> Map a b
757 hedgeDiffWithKey _ _ _ Tip _
758 = Tip
759 hedgeDiffWithKey _ blo bhi (Bin _ kx x l r) Tip
760 = join kx x (filterGt blo l) (filterLt bhi r)
761 hedgeDiffWithKey f blo bhi t (Bin _ kx x l r)
762 = case found of
763 Nothing -> merge tl tr
764 Just (ky,y) ->
765 case f ky y x of
766 Nothing -> merge tl tr
767 Just !z -> join ky z tl tr
768 where
769 bmi = JustS kx
770 lt = trim blo bmi t
771 (found,gt) = trimLookupLo kx bhi t
772 tl = hedgeDiffWithKey f blo bmi lt l
773 tr = hedgeDiffWithKey f bmi bhi gt r
774 #if __GLASGOW_HASKELL__ >= 700
775 {-# INLINABLE hedgeDiffWithKey #-}
776 #endif
777
778 {--------------------------------------------------------------------
779 Intersection
780 --------------------------------------------------------------------}
781
782 -- | /O(n+m)/. Intersection with a combining function.
783 --
784 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
785
786 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
787 intersectionWith f m1 m2
788 = intersectionWithKey (\_ x y -> f x y) m1 m2
789 {-# INLINE intersectionWith #-}
790
791 -- | /O(n+m)/. Intersection with a combining function.
792 -- Intersection is more efficient on (bigset \``intersection`\` smallset).
793 --
794 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
795 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
796
797
798 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
799 intersectionWithKey _ Tip _ = Tip
800 intersectionWithKey _ _ Tip = Tip
801 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
802 if s1 >= s2 then
803 let (lt,found,gt) = splitLookupWithKey k2 t1
804 tl = intersectionWithKey f lt l2
805 tr = intersectionWithKey f gt r2
806 in case found of
807 Just (k,x) -> join k (f k x x2) tl tr
808 Nothing -> merge tl tr
809 else let (lt,found,gt) = splitLookup k1 t2
810 tl = intersectionWithKey f l1 lt
811 tr = intersectionWithKey f r1 gt
812 in case found of
813 Just x -> let !x' = f k1 x1 x in join k1 x' tl tr
814 Nothing -> merge tl tr
815 #if __GLASGOW_HASKELL__ >= 700
816 {-# INLINABLE intersectionWithKey #-}
817 #endif
818
819 {--------------------------------------------------------------------
820 Filter and partition
821 --------------------------------------------------------------------}
822
823 -- | /O(n)/. Map values and collect the 'Just' results.
824 --
825 -- > let f x = if x == "a" then Just "new a" else Nothing
826 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
827
828 mapMaybe :: Ord k => (a -> Maybe b) -> Map k a -> Map k b
829 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
830 #if __GLASGOW_HASKELL__ >= 700
831 {-# INLINABLE mapMaybe #-}
832 #endif
833
834 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
835 --
836 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
837 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
838
839 mapMaybeWithKey :: Ord k => (k -> a -> Maybe b) -> Map k a -> Map k b
840 mapMaybeWithKey _ Tip = Tip
841 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
842 Just !y -> join kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
843 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
844 #if __GLASGOW_HASKELL__ >= 700
845 {-# INLINABLE mapMaybeWithKey #-}
846 #endif
847
848 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
849 --
850 -- > let f a = if a < "c" then Left a else Right a
851 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
852 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
853 -- >
854 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
855 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
856
857 mapEither :: Ord k => (a -> Either b c) -> Map k a -> (Map k b, Map k c)
858 mapEither f m
859 = mapEitherWithKey (\_ x -> f x) m
860 #if __GLASGOW_HASKELL__ >= 700
861 {-# INLINABLE mapEither #-}
862 #endif
863
864 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
865 --
866 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
867 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
868 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
869 -- >
870 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
871 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
872
873 mapEitherWithKey :: Ord k =>
874 (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
875 mapEitherWithKey _ Tip = (Tip, Tip)
876 mapEitherWithKey f (Bin _ kx x l r) = case f kx x of
877 Left !y -> let !l' = join kx y l1 r1
878 !r' = merge l2 r2
879 in (l', r')
880 Right !z -> let !l' = merge l1 r1
881 !r' = join kx z l2 r2
882 in (l', r')
883 where
884 (l1,l2) = mapEitherWithKey f l
885 (r1,r2) = mapEitherWithKey f r
886 #if __GLASGOW_HASKELL__ >= 700
887 {-# INLINABLE mapEitherWithKey #-}
888 #endif
889
890 {--------------------------------------------------------------------
891 Mapping
892 --------------------------------------------------------------------}
893 -- | /O(n)/. Map a function over all values in the map.
894 --
895 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
896
897 map :: (a -> b) -> Map k a -> Map k b
898 map f = mapWithKey (\_ x -> f x)
899 #if __GLASGOW_HASKELL__ >= 700
900 {-# INLINABLE map #-}
901 #endif
902
903 -- | /O(n)/. Map a function over all values in the map.
904 --
905 -- > let f key x = (show key) ++ ":" ++ x
906 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
907
908 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
909 mapWithKey _ Tip = Tip
910 mapWithKey f (Bin sx kx x l r) = let !x' = f kx x
911 in Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
912 #if __GLASGOW_HASKELL__ >= 700
913 {-# INLINABLE mapWithKey #-}
914 #endif
915
916 -- | /O(n)/. The function 'mapAccum' threads an accumulating
917 -- argument through the map in ascending order of keys.
918 --
919 -- > let f a b = (a ++ b, b ++ "X")
920 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
921
922 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
923 mapAccum f a m
924 = mapAccumWithKey (\a' _ x' -> f a' x') a m
925 #if __GLASGOW_HASKELL__ >= 700
926 {-# INLINABLE mapAccum #-}
927 #endif
928
929 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
930 -- argument through the map in ascending order of keys.
931 --
932 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
933 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
934
935 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
936 mapAccumWithKey f a t
937 = mapAccumL f a t
938 #if __GLASGOW_HASKELL__ >= 700
939 {-# INLINABLE mapAccumWithKey #-}
940 #endif
941
942 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
943 -- argument through the map in ascending order of keys.
944 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
945 mapAccumL _ a Tip = (a,Tip)
946 mapAccumL f a (Bin sx kx x l r) =
947 let (a1,l') = mapAccumL f a l
948 (a2,!x') = f a1 kx x
949 (a3,r') = mapAccumL f a2 r
950 in (a3,Bin sx kx x' l' r')
951 #if __GLASGOW_HASKELL__ >= 700
952 {-# INLINABLE mapAccumL #-}
953 #endif
954
955 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
956 -- argument through the map in descending order of keys.
957 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
958 mapAccumRWithKey _ a Tip = (a,Tip)
959 mapAccumRWithKey f a (Bin sx kx x l r) =
960 let (a1,r') = mapAccumRWithKey f a r
961 (a2,!x') = f a1 kx x
962 (a3,l') = mapAccumRWithKey f a2 l
963 in (a3,Bin sx kx x' l' r')
964 #if __GLASGOW_HASKELL__ >= 700
965 {-# INLINABLE mapAccumRWithKey #-}
966 #endif
967
968 -- | /O(n*log n)/.
969 -- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
970 --
971 -- The size of the result may be smaller if @f@ maps two or more distinct
972 -- keys to the same new key. In this case the value at the smallest of
973 -- these keys is retained.
974 --
975 -- > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")]) == fromList [(4, "b"), (6, "a")]
976 -- > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
977 -- > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"
978
979 mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
980 mapKeys = mapKeysWith (\x _ -> x)
981 #if __GLASGOW_HASKELL__ >= 700
982 {-# INLINABLE mapKeys #-}
983 #endif
984
985 -- | /O(n*log n)/.
986 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
987 --
988 -- The size of the result may be smaller if @f@ maps two or more distinct
989 -- keys to the same new key. In this case the associated values will be
990 -- combined using @c@.
991 --
992 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
993 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
994
995 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
996 mapKeysWith c f = fromListWith c . List.map fFirst . toList
997 where fFirst (x,y) = (f x, y)
998 #if __GLASGOW_HASKELL__ >= 700
999 {-# INLINABLE mapKeysWith #-}
1000 #endif
1001
1002
1003 -- | /O(n)/.
1004 -- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
1005 -- is strictly monotonic.
1006 -- That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@.
1007 -- /The precondition is not checked./
1008 -- Semi-formally, we have:
1009 --
1010 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
1011 -- > ==> mapKeysMonotonic f s == mapKeys f s
1012 -- > where ls = keys s
1013 --
1014 -- This means that @f@ maps distinct original keys to distinct resulting keys.
1015 -- This function has better performance than 'mapKeys'.
1016 --
1017 -- > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]
1018 -- > valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True
1019 -- > valid (mapKeysMonotonic (\ _ -> 1) (fromList [(5,"a"), (3,"b")])) == False
1020
1021 mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
1022 mapKeysMonotonic _ Tip = Tip
1023 mapKeysMonotonic f (Bin sz k x l r) =
1024 let !k' = f k
1025 in Bin sz k' x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
1026 #if __GLASGOW_HASKELL__ >= 700
1027 {-# INLINABLE mapKeysMonotonic #-}
1028 #endif
1029
1030 {--------------------------------------------------------------------
1031 Lists
1032 use [foldlStrict] to reduce demand on the control-stack
1033 --------------------------------------------------------------------}
1034 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1035 -- If the list contains more than one value for the same key, the last value
1036 -- for the key is retained.
1037 --
1038 -- > fromList [] == empty
1039 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1040 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1041
1042 fromList :: Ord k => [(k,a)] -> Map k a
1043 fromList xs
1044 = foldlStrict ins empty xs
1045 where
1046 ins t (k,x) = insert k x t
1047 #if __GLASGOW_HASKELL__ >= 700
1048 {-# INLINABLE fromList #-}
1049 #endif
1050
1051 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1052 --
1053 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1054 -- > fromListWith (++) [] == empty
1055
1056 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1057 fromListWith f xs
1058 = fromListWithKey (\_ x y -> f x y) xs
1059 #if __GLASGOW_HASKELL__ >= 700
1060 {-# INLINABLE fromListWith #-}
1061 #endif
1062
1063 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1064 --
1065 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1066 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1067 -- > fromListWithKey f [] == empty
1068
1069 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1070 fromListWithKey f xs
1071 = foldlStrict ins empty xs
1072 where
1073 ins t (k,x) = insertWithKey f k x t
1074 #if __GLASGOW_HASKELL__ >= 700
1075 {-# INLINABLE fromListWithKey #-}
1076 #endif
1077
1078 {--------------------------------------------------------------------
1079 Building trees from ascending/descending lists can be done in linear time.
1080
1081 Note that if [xs] is ascending that:
1082 fromAscList xs == fromList xs
1083 fromAscListWith f xs == fromListWith f xs
1084 --------------------------------------------------------------------}
1085 -- | /O(n)/. Build a map from an ascending list in linear time.
1086 -- /The precondition (input list is ascending) is not checked./
1087 --
1088 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1089 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1090 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1091 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1092
1093 fromAscList :: Eq k => [(k,a)] -> Map k a
1094 fromAscList xs
1095 = fromAscListWithKey (\_ x _ -> x) xs
1096 #if __GLASGOW_HASKELL__ >= 700
1097 {-# INLINABLE fromAscList #-}
1098 #endif
1099
1100 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1101 -- /The precondition (input list is ascending) is not checked./
1102 --
1103 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1104 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1105 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1106
1107 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1108 fromAscListWith f xs
1109 = fromAscListWithKey (\_ x y -> f x y) xs
1110 #if __GLASGOW_HASKELL__ >= 700
1111 {-# INLINABLE fromAscListWith #-}
1112 #endif
1113
1114 -- | /O(n)/. Build a map from an ascending list in linear time with a
1115 -- combining function for equal keys.
1116 -- /The precondition (input list is ascending) is not checked./
1117 --
1118 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1119 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1120 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1121 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1122
1123 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1124 fromAscListWithKey f xs
1125 = fromDistinctAscList (combineEq f xs)
1126 where
1127 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1128 combineEq _ xs'
1129 = case xs' of
1130 [] -> []
1131 [x] -> [x]
1132 (x:xx) -> combineEq' x xx
1133
1134 combineEq' z [] = [z]
1135 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1136 | kx==kz = let !yy = f kx xx zz in combineEq' (kx,yy) xs'
1137 | otherwise = z:combineEq' x xs'
1138 #if __GLASGOW_HASKELL__ >= 700
1139 {-# INLINABLE fromAscListWithKey #-}
1140 #endif
1141
1142 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1143 -- /The precondition is not checked./
1144 --
1145 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1146 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1147 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1148
1149 fromDistinctAscList :: [(k,a)] -> Map k a
1150 fromDistinctAscList xs
1151 = build const (length xs) xs
1152 where
1153 -- 1) use continuations so that we use heap space instead of stack space.
1154 -- 2) special case for n==5 to build bushier trees.
1155 build c 0 xs' = c Tip xs'
1156 build c 5 xs' = case xs' of
1157 ((k1,!x1):(k2,!x2):(k3,!x3):(k4,!x4):(k5,!x5):xx)
1158 -> c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3)) (singleton k5 x5)) xx
1159 _ -> error "fromDistinctAscList build"
1160 build c n xs' = seq nr $ build (buildR nr c) nl xs'
1161 where
1162 nl = n `div` 2
1163 nr = n - nl - 1
1164
1165 buildR n c l ((k,!x):ys) = build (buildB l k x c) n ys
1166 buildR _ _ _ [] = error "fromDistinctAscList buildR []"
1167 buildB l k !x c r zs = c (bin k x l r) zs
1168 #if __GLASGOW_HASKELL__ >= 700
1169 {-# INLINABLE fromDistinctAscList #-}
1170 #endif