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