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