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