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