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