fix typo in documentation
[packages/containers.git] / Data / Map / Strict.hs
1 {-# LANGUAGE CPP #-}
2 #if !defined(TESTING) && __GLASGOW_HASKELL__ >= 703
3 {-# LANGUAGE Trustworthy #-}
4 #endif
5
6 #include "containers.h"
7
8 -----------------------------------------------------------------------------
9 -- |
10 -- Module : Data.Map.Strict
11 -- Copyright : (c) Daan Leijen 2002
12 -- (c) Andriy Palamarchuk 2008
13 -- License : BSD-style
14 -- Maintainer : libraries@haskell.org
15 -- Stability : provisional
16 -- Portability : portable
17 --
18 -- An efficient implementation of ordered maps from keys to values
19 -- (dictionaries).
20 --
21 -- API of this module is strict in both the keys and the values.
22 -- If you need value-lazy maps, use "Data.Map.Lazy" instead.
23 -- The 'Map' type is shared between the lazy and strict modules,
24 -- meaning that the same 'Map' value can be passed to functions in
25 -- both modules (although that is rarely needed).
26 --
27 -- These modules are intended to be imported qualified, to avoid name
28 -- clashes with Prelude functions, e.g.
29 --
30 -- > import qualified Data.Map.Strict as Map
31 --
32 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
33 -- trees of /bounded balance/) as described by:
34 --
35 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
36 -- Journal of Functional Programming 3(4):553-562, October 1993,
37 -- <http://www.swiss.ai.mit.edu/~adams/BB/>.
38 --
39 -- * J. Nievergelt and E.M. Reingold,
40 -- \"/Binary search trees of bounded balance/\",
41 -- SIAM journal of computing 2(1), March 1973.
42 --
43 -- Note that the implementation is /left-biased/ -- the elements of a
44 -- first argument are always preferred to the second, for example in
45 -- 'union' or 'insert'.
46 --
47 -- /Warning/: The size of the map must not exceed @maxBound::Int@. Violation of
48 -- this condition is not detected and if the size limit is exceeded, its
49 -- behaviour is undefined.
50 --
51 -- Operation comments contain the operation time complexity in
52 -- the Big-O notation (<http://en.wikipedia.org/wiki/Big_O_notation>).
53 --
54 -- Be aware that the 'Functor', 'Traversable' and 'Data' instances
55 -- are the same as for the "Data.Map.Lazy" module, so if they are used
56 -- on strict maps, the resulting maps will be lazy.
57 -----------------------------------------------------------------------------
58
59 -- See the notes at the beginning of Data.Map.Base.
60
61 module Data.Map.Strict
62 (
63 -- * Strictness properties
64 -- $strictness
65
66 -- * Map type
67 #if !defined(TESTING)
68 Map -- instance Eq,Show,Read
69 #else
70 Map(..) -- instance Eq,Show,Read
71 #endif
72
73 -- * Operators
74 , (!), (\\)
75
76 -- * Query
77 , null
78 , size
79 , member
80 , notMember
81 , lookup
82 , findWithDefault
83 , lookupLT
84 , lookupGT
85 , lookupLE
86 , lookupGE
87
88 -- * Construction
89 , empty
90 , singleton
91
92 -- ** Insertion
93 , insert
94 , insertWith
95 , insertWithKey
96 , insertLookupWithKey
97
98 -- ** Delete\/Update
99 , delete
100 , adjust
101 , adjustWithKey
102 , update
103 , updateWithKey
104 , updateLookupWithKey
105 , alter
106
107 -- * Combine
108
109 -- ** Union
110 , union
111 , unionWith
112 , unionWithKey
113 , unions
114 , unionsWith
115
116 -- ** Difference
117 , difference
118 , differenceWith
119 , differenceWithKey
120
121 -- ** Intersection
122 , intersection
123 , intersectionWith
124 , intersectionWithKey
125
126 -- ** Universal combining function
127 , mergeWithKey
128
129 -- * Traversal
130 -- ** Map
131 , map
132 , mapWithKey
133 , traverseWithKey
134 , mapAccum
135 , mapAccumWithKey
136 , mapAccumRWithKey
137 , mapKeys
138 , mapKeysWith
139 , mapKeysMonotonic
140
141 -- * Folds
142 , foldr
143 , foldl
144 , foldrWithKey
145 , foldlWithKey
146 , foldMapWithKey
147
148 -- ** Strict folds
149 , foldr'
150 , foldl'
151 , foldrWithKey'
152 , foldlWithKey'
153
154 -- * Conversion
155 , elems
156 , keys
157 , assocs
158 , keysSet
159 , fromSet
160
161 -- ** Lists
162 , toList
163 , fromList
164 , fromListWith
165 , fromListWithKey
166
167 -- ** Ordered lists
168 , toAscList
169 , toDescList
170 , fromAscList
171 , fromAscListWith
172 , fromAscListWithKey
173 , fromDistinctAscList
174
175 -- * Filter
176 , filter
177 , filterWithKey
178 , partition
179 , partitionWithKey
180
181 , mapMaybe
182 , mapMaybeWithKey
183 , mapEither
184 , mapEitherWithKey
185
186 , split
187 , splitLookup
188 , splitRoot
189
190 -- * Submap
191 , isSubmapOf, isSubmapOfBy
192 , isProperSubmapOf, isProperSubmapOfBy
193
194 -- * Indexed
195 , lookupIndex
196 , findIndex
197 , elemAt
198 , updateAt
199 , deleteAt
200
201 -- * Min\/Max
202 , findMin
203 , findMax
204 , deleteMin
205 , deleteMax
206 , deleteFindMin
207 , deleteFindMax
208 , updateMin
209 , updateMax
210 , updateMinWithKey
211 , updateMaxWithKey
212 , minView
213 , maxView
214 , minViewWithKey
215 , maxViewWithKey
216
217 -- * Debugging
218 , showTree
219 , showTreeWith
220 , valid
221
222 #if defined(TESTING)
223 -- * Internals
224 , bin
225 , balanced
226 , link
227 , merge
228 #endif
229 ) where
230
231 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
232
233 import Data.Map.Base hiding
234 ( findWithDefault
235 , singleton
236 , insert
237 , insertWith
238 , insertWithKey
239 , insertLookupWithKey
240 , adjust
241 , adjustWithKey
242 , update
243 , updateWithKey
244 , updateLookupWithKey
245 , alter
246 , unionWith
247 , unionWithKey
248 , unionsWith
249 , differenceWith
250 , differenceWithKey
251 , intersectionWith
252 , intersectionWithKey
253 , mergeWithKey
254 , map
255 , mapWithKey
256 , mapAccum
257 , mapAccumWithKey
258 , mapAccumRWithKey
259 , mapKeysWith
260 , fromSet
261 , fromList
262 , fromListWith
263 , fromListWithKey
264 , fromAscList
265 , fromAscListWith
266 , fromAscListWithKey
267 , fromDistinctAscList
268 , mapMaybe
269 , mapMaybeWithKey
270 , mapEither
271 , mapEitherWithKey
272 , updateAt
273 , updateMin
274 , updateMax
275 , updateMinWithKey
276 , updateMaxWithKey
277 )
278 import qualified Data.Set.Base as Set
279 import Data.Utils.StrictFold
280 import Data.Utils.StrictPair
281
282 import Data.Bits (shiftL, shiftR)
283 #if __GLASGOW_HASKELL__ >= 709
284 import Data.Coerce
285 #endif
286
287
288 -- $strictness
289 --
290 -- This module satisfies the following strictness properties:
291 --
292 -- 1. Key arguments are evaluated to WHNF;
293 --
294 -- 2. Keys and values are evaluated to WHNF before they are stored in
295 -- the map.
296 --
297 -- Here's an example illustrating the first property:
298 --
299 -- > delete undefined m == undefined
300 --
301 -- Here are some examples that illustrate the second property:
302 --
303 -- > map (\ v -> undefined) m == undefined -- m is not empty
304 -- > mapKeys (\ k -> undefined) m == undefined -- m is not empty
305
306 {--------------------------------------------------------------------
307 Query
308 --------------------------------------------------------------------}
309
310 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
311 -- the value at key @k@ or returns default value @def@
312 -- when the key is not in the map.
313 --
314 -- > findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
315 -- > findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'
316
317 -- See Map.Base.Note: Local 'go' functions and capturing
318 findWithDefault :: Ord k => a -> k -> Map k a -> a
319 findWithDefault def k = k `seq` go
320 where
321 go Tip = def
322 go (Bin _ kx x l r) = case compare k kx of
323 LT -> go l
324 GT -> go r
325 EQ -> x
326 #if __GLASGOW_HASKELL__ >= 700
327 {-# INLINABLE findWithDefault #-}
328 #else
329 {-# INLINE findWithDefault #-}
330 #endif
331
332 {--------------------------------------------------------------------
333 Construction
334 --------------------------------------------------------------------}
335
336 -- | /O(1)/. A map with a single element.
337 --
338 -- > singleton 1 'a' == fromList [(1, 'a')]
339 -- > size (singleton 1 'a') == 1
340
341 singleton :: k -> a -> Map k a
342 singleton k x = x `seq` Bin 1 k x Tip Tip
343 {-# INLINE singleton #-}
344
345 {--------------------------------------------------------------------
346 Insertion
347 --------------------------------------------------------------------}
348 -- | /O(log n)/. Insert a new key and value in the map.
349 -- If the key is already present in the map, the associated value is
350 -- replaced with the supplied value. 'insert' is equivalent to
351 -- @'insertWith' 'const'@.
352 --
353 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
354 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
355 -- > insert 5 'x' empty == singleton 5 'x'
356
357 -- See Map.Base.Note: Type of local 'go' function
358 insert :: Ord k => k -> a -> Map k a -> Map k a
359 insert = go
360 where
361 go :: Ord k => k -> a -> Map k a -> Map k a
362 STRICT_1_OF_3(go)
363 STRICT_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 -- 'Map'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 #ifdef __GLASGOW_HASKELL__
930 {-# NOINLINE [1] map #-}
931 {-# RULES
932 "map/map" forall f g xs . map f (map g xs) = map (f . g) xs
933 #-}
934 #endif
935 #if __GLASGOW_HASKELL__ >= 709
936 -- Safe coercions were introduced in 7.8, but did not work well with RULES yet.
937 {-# RULES
938 "mapSeq/coerce" map coerce = coerce
939 #-}
940 #endif
941
942 -- | /O(n)/. Map a function over all values in the map.
943 --
944 -- > let f key x = (show key) ++ ":" ++ x
945 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
946
947 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
948 mapWithKey _ Tip = Tip
949 mapWithKey f (Bin sx kx x l r) =
950 let x' = f kx x
951 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
952
953 #ifdef __GLASGOW_HASKELL__
954 {-# NOINLINE [1] mapWithKey #-}
955 {-# RULES
956 "mapWithKey/mapWithKey" forall f g xs . mapWithKey f (mapWithKey g xs) =
957 mapWithKey (\k a -> f k (g k a)) xs
958 "mapWithKey/map" forall f g xs . mapWithKey f (map g xs) =
959 mapWithKey (\k a -> f k (g a)) xs
960 "map/mapWithKey" forall f g xs . map f (mapWithKey g xs) =
961 mapWithKey (\k a -> f (g k a)) xs
962 #-}
963 #endif
964
965 -- | /O(n)/. The function 'mapAccum' threads an accumulating
966 -- argument through the map in ascending order of keys.
967 --
968 -- > let f a b = (a ++ b, b ++ "X")
969 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
970
971 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
972 mapAccum f a m
973 = mapAccumWithKey (\a' _ x' -> f a' x') a m
974
975 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
976 -- argument through the map in ascending order of keys.
977 --
978 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
979 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
980
981 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
982 mapAccumWithKey f a t
983 = mapAccumL f a t
984
985 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
986 -- argument through the map in ascending order of keys.
987 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
988 mapAccumL _ a Tip = (a,Tip)
989 mapAccumL f a (Bin sx kx x l r) =
990 let (a1,l') = mapAccumL f a l
991 (a2,x') = f a1 kx x
992 (a3,r') = mapAccumL f a2 r
993 in x' `seq` (a3,Bin sx kx x' l' r')
994
995 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
996 -- argument through the map in descending order of keys.
997 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
998 mapAccumRWithKey _ a Tip = (a,Tip)
999 mapAccumRWithKey f a (Bin sx kx x l r) =
1000 let (a1,r') = mapAccumRWithKey f a r
1001 (a2,x') = f a1 kx x
1002 (a3,l') = mapAccumRWithKey f a2 l
1003 in x' `seq` (a3,Bin sx kx x' l' r')
1004
1005 -- | /O(n*log n)/.
1006 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
1007 --
1008 -- The size of the result may be smaller if @f@ maps two or more distinct
1009 -- keys to the same new key. In this case the associated values will be
1010 -- combined using @c@.
1011 --
1012 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
1013 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
1014
1015 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
1016 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
1017 #if __GLASGOW_HASKELL__ >= 700
1018 {-# INLINABLE mapKeysWith #-}
1019 #endif
1020
1021 {--------------------------------------------------------------------
1022 Conversions
1023 --------------------------------------------------------------------}
1024
1025 -- | /O(n)/. Build a map from a set of keys and a function which for each key
1026 -- computes its value.
1027 --
1028 -- > fromSet (\k -> replicate k 'a') (Data.Set.fromList [3, 5]) == fromList [(5,"aaaaa"), (3,"aaa")]
1029 -- > fromSet undefined Data.Set.empty == empty
1030
1031 fromSet :: (k -> a) -> Set.Set k -> Map k a
1032 fromSet _ Set.Tip = Tip
1033 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)
1034
1035 {--------------------------------------------------------------------
1036 Lists
1037 use [foldlStrict] to reduce demand on the control-stack
1038 --------------------------------------------------------------------}
1039 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1040 -- If the list contains more than one value for the same key, the last value
1041 -- for the key is retained.
1042 --
1043 -- If the keys of the list are ordered, linear-time implementation is used,
1044 -- with the performance equal to 'fromDistinctAscList'.
1045 --
1046 -- > fromList [] == empty
1047 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
1048 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
1049
1050 -- For some reason, when 'singleton' is used in fromList or in
1051 -- create, it is not inlined, so we inline it manually.
1052 fromList :: Ord k => [(k,a)] -> Map k a
1053 fromList [] = Tip
1054 fromList [(kx, x)] = x `seq` Bin 1 kx x Tip Tip
1055 fromList ((kx0, x0) : xs0) | not_ordered kx0 xs0 = x0 `seq` fromList' (Bin 1 kx0 x0 Tip Tip) xs0
1056 | otherwise = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1057 where
1058 not_ordered _ [] = False
1059 not_ordered kx ((ky,_) : _) = kx >= ky
1060 {-# INLINE not_ordered #-}
1061
1062 fromList' t0 xs = foldlStrict ins t0 xs
1063 where ins t (k,x) = insert k x t
1064
1065 STRICT_1_OF_3(go)
1066 go _ t [] = t
1067 go _ t [(kx, x)] = x `seq` insertMax kx x t
1068 go s l xs@((kx, x) : xss) | not_ordered kx xss = fromList' l xs
1069 | otherwise = case create s xss of
1070 (r, ys, []) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1071 (r, _, ys) -> x `seq` fromList' (link kx x l r) ys
1072
1073 -- The create is returning a triple (tree, xs, ys). Both xs and ys
1074 -- represent not yet processed elements and only one of them can be nonempty.
1075 -- If ys is nonempty, the keys in ys are not ordered with respect to tree
1076 -- and must be inserted using fromList'. Otherwise the keys have been
1077 -- ordered so far.
1078 STRICT_1_OF_2(create)
1079 create _ [] = (Tip, [], [])
1080 create s xs@(xp : xss)
1081 | s == 1 = case xp of (kx, x) | not_ordered kx xss -> x `seq` (Bin 1 kx x Tip Tip, [], xss)
1082 | otherwise -> x `seq` (Bin 1 kx x Tip Tip, xss, [])
1083 | otherwise = case create (s `shiftR` 1) xs of
1084 res@(_, [], _) -> res
1085 (l, [(ky, y)], zs) -> y `seq` (insertMax ky y l, [], zs)
1086 (l, ys@((ky, y):yss), _) | not_ordered ky yss -> (l, [], ys)
1087 | otherwise -> case create (s `shiftR` 1) yss of
1088 (r, zs, ws) -> y `seq` (link ky y l r, zs, ws)
1089 #if __GLASGOW_HASKELL__ >= 700
1090 {-# INLINABLE fromList #-}
1091 #endif
1092
1093 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1094 --
1095 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
1096 -- > fromListWith (++) [] == empty
1097
1098 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1099 fromListWith f xs
1100 = fromListWithKey (\_ x y -> f x y) xs
1101 #if __GLASGOW_HASKELL__ >= 700
1102 {-# INLINABLE fromListWith #-}
1103 #endif
1104
1105 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1106 --
1107 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
1108 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
1109 -- > fromListWithKey f [] == empty
1110
1111 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1112 fromListWithKey f xs
1113 = foldlStrict ins empty xs
1114 where
1115 ins t (k,x) = insertWithKey f k x t
1116 #if __GLASGOW_HASKELL__ >= 700
1117 {-# INLINABLE fromListWithKey #-}
1118 #endif
1119
1120 {--------------------------------------------------------------------
1121 Building trees from ascending/descending lists can be done in linear time.
1122
1123 Note that if [xs] is ascending that:
1124 fromAscList xs == fromList xs
1125 fromAscListWith f xs == fromListWith f xs
1126 --------------------------------------------------------------------}
1127 -- | /O(n)/. Build a map from an ascending list in linear time.
1128 -- /The precondition (input list is ascending) is not checked./
1129 --
1130 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1131 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1132 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1133 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1134
1135 fromAscList :: Eq k => [(k,a)] -> Map k a
1136 fromAscList xs
1137 = fromAscListWithKey (\_ x _ -> x) xs
1138 #if __GLASGOW_HASKELL__ >= 700
1139 {-# INLINABLE fromAscList #-}
1140 #endif
1141
1142 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1143 -- /The precondition (input list is ascending) is not checked./
1144 --
1145 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1146 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1147 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1148
1149 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1150 fromAscListWith f xs
1151 = fromAscListWithKey (\_ x y -> f x y) xs
1152 #if __GLASGOW_HASKELL__ >= 700
1153 {-# INLINABLE fromAscListWith #-}
1154 #endif
1155
1156 -- | /O(n)/. Build a map from an ascending list in linear time with a
1157 -- combining function for equal keys.
1158 -- /The precondition (input list is ascending) is not checked./
1159 --
1160 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1161 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1162 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1163 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1164
1165 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1166 fromAscListWithKey f xs
1167 = fromDistinctAscList (combineEq f xs)
1168 where
1169 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1170 combineEq _ xs'
1171 = case xs' of
1172 [] -> []
1173 [x] -> [x]
1174 (x:xx) -> combineEq' x xx
1175
1176 combineEq' z [] = [z]
1177 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1178 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1179 | otherwise = z:combineEq' x xs'
1180 #if __GLASGOW_HASKELL__ >= 700
1181 {-# INLINABLE fromAscListWithKey #-}
1182 #endif
1183
1184 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1185 -- /The precondition is not checked./
1186 --
1187 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1188 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1189 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1190
1191 -- For some reason, when 'singleton' is used in fromDistinctAscList or in
1192 -- create, it is not inlined, so we inline it manually.
1193 fromDistinctAscList :: [(k,a)] -> Map k a
1194 fromDistinctAscList [] = Tip
1195 fromDistinctAscList ((kx0, x0) : xs0) = x0 `seq` go (1::Int) (Bin 1 kx0 x0 Tip Tip) xs0
1196 where
1197 STRICT_1_OF_3(go)
1198 go _ t [] = t
1199 go s l ((kx, x) : xs) = case create s xs of
1200 (r, ys) -> x `seq` go (s `shiftL` 1) (link kx x l r) ys
1201
1202 STRICT_1_OF_2(create)
1203 create _ [] = (Tip, [])
1204 create s xs@(x' : xs')
1205 | s == 1 = case x' of (kx, x) -> x `seq` (Bin 1 kx x Tip Tip, xs')
1206 | otherwise = case create (s `shiftR` 1) xs of
1207 res@(_, []) -> res
1208 (l, (ky, y):ys) -> case create (s `shiftR` 1) ys of
1209 (r, zs) -> y `seq` (link ky y l r, zs)