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