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