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