Improve programming documentation.
[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.IntMap.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 findWithDefault :: Ord k => a -> k -> Map k a -> a
301 findWithDefault def k m = def `seq` case lookup k m of
302 Nothing -> def
303 Just x -> x
304 #if __GLASGOW_HASKELL__ >= 700
305 {-# INLINABLE findWithDefault #-}
306 #else
307 {-# INLINE findWithDefault #-}
308 #endif
309
310 {--------------------------------------------------------------------
311 Construction
312 --------------------------------------------------------------------}
313
314 -- | /O(1)/. A map with a single element.
315 --
316 -- > singleton 1 'a' == fromList [(1, 'a')]
317 -- > size (singleton 1 'a') == 1
318
319 singleton :: k -> a -> Map k a
320 singleton k x = x `seq` Bin 1 k x Tip Tip
321 {-# INLINE singleton #-}
322
323 {--------------------------------------------------------------------
324 Insertion
325 --------------------------------------------------------------------}
326 -- | /O(log n)/. Insert a new key and value in the map.
327 -- If the key is already present in the map, the associated value is
328 -- replaced with the supplied value. 'insert' is equivalent to
329 -- @'insertWith' 'const'@.
330 --
331 -- > insert 5 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'x')]
332 -- > insert 7 'x' (fromList [(5,'a'), (3,'b')]) == fromList [(3, 'b'), (5, 'a'), (7, 'x')]
333 -- > insert 5 'x' empty == singleton 5 'x'
334
335 insert :: Ord k => k -> a -> Map k a -> Map k a
336 insert = go
337 where
338 STRICT_1_2_OF_3(go)
339 go kx x Tip = singleton kx x
340 go kx x (Bin sz ky y l r) =
341 case compare kx ky of
342 LT -> balanceL ky y (go kx x l) r
343 GT -> balanceR ky y l (go kx x r)
344 EQ -> Bin sz kx x l r
345 #if __GLASGOW_HASKELL__ >= 700
346 {-# INLINABLE insert #-}
347 #else
348 {-# INLINE insert #-}
349 #endif
350
351 -- | /O(log n)/. Insert with a function, combining new value and old value.
352 -- @'insertWith' f key value mp@
353 -- will insert the pair (key, value) into @mp@ if key does
354 -- not exist in the map. If the key does exist, the function will
355 -- insert the pair @(key, f new_value old_value)@.
356 --
357 -- > insertWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
358 -- > insertWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
359 -- > insertWith (++) 5 "xxx" empty == singleton 5 "xxx"
360
361 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
362 insertWith f = insertWithKey (\_ x' y' -> f x' y')
363 #if __GLASGOW_HASKELL__ >= 700
364 {-# INLINABLE insertWith #-}
365 #else
366 {-# INLINE insertWith #-}
367 #endif
368
369 -- | /O(log n)/. Insert with a function, combining key, new value and old value.
370 -- @'insertWithKey' f key value mp@
371 -- will insert the pair (key, value) into @mp@ if key does
372 -- not exist in the map. If the key does exist, the function will
373 -- insert the pair @(key,f key new_value old_value)@.
374 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
375 --
376 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
377 -- > insertWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
378 -- > insertWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
379 -- > insertWithKey f 5 "xxx" empty == singleton 5 "xxx"
380
381 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
382 insertWithKey = go
383 where
384 STRICT_2_3_OF_4(go)
385 go _ kx x Tip = singleton kx x
386 go f kx x (Bin sy ky y l r) =
387 case compare kx ky of
388 LT -> balanceL ky y (go f kx x l) r
389 GT -> balanceR ky y l (go f kx x r)
390 EQ -> let x' = f kx x y
391 in x' `seq` Bin sy kx x' l r
392 #if __GLASGOW_HASKELL__ >= 700
393 {-# INLINABLE insertWithKey #-}
394 #else
395 {-# INLINE insertWithKey #-}
396 #endif
397
398 -- | /O(log n)/. Combines insert operation with old value retrieval.
399 -- The expression (@'insertLookupWithKey' f k x map@)
400 -- is a pair where the first element is equal to (@'lookup' k map@)
401 -- and the second element equal to (@'insertWithKey' f k x map@).
402 --
403 -- > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
404 -- > insertLookupWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "5:xxx|a")])
405 -- > insertLookupWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "xxx")])
406 -- > insertLookupWithKey f 5 "xxx" empty == (Nothing, singleton 5 "xxx")
407 --
408 -- This is how to define @insertLookup@ using @insertLookupWithKey@:
409 --
410 -- > let insertLookup kx x t = insertLookupWithKey (\_ a _ -> a) kx x t
411 -- > insertLookup 5 "x" (fromList [(5,"a"), (3,"b")]) == (Just "a", fromList [(3, "b"), (5, "x")])
412 -- > insertLookup 7 "x" (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a"), (7, "x")])
413
414 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a
415 -> (Maybe a, Map k a)
416 insertLookupWithKey = go
417 where
418 STRICT_2_3_OF_4(go)
419 go _ kx x Tip = Nothing `strictPair` singleton kx x
420 go f kx x (Bin sy ky y l r) =
421 case compare kx ky of
422 LT -> let (found, l') = go f kx x l
423 in found `strictPair` balanceL ky y l' r
424 GT -> let (found, r') = go f kx x r
425 in found `strictPair` balanceR ky y l r'
426 EQ -> let x' = f kx x y
427 in x' `seq` (Just y `strictPair` Bin sy kx x' l r)
428 #if __GLASGOW_HASKELL__ >= 700
429 {-# INLINABLE insertLookupWithKey #-}
430 #else
431 {-# INLINE insertLookupWithKey #-}
432 #endif
433
434 {--------------------------------------------------------------------
435 Deletion
436 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
437 --------------------------------------------------------------------}
438
439 -- | /O(log n)/. Update a value at a specific key with the result of the provided function.
440 -- When the key is not
441 -- a member of the map, the original map is returned.
442 --
443 -- > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
444 -- > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
445 -- > adjust ("new " ++) 7 empty == empty
446
447 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
448 adjust f = adjustWithKey (\_ x -> f x)
449 #if __GLASGOW_HASKELL__ >= 700
450 {-# INLINABLE adjust #-}
451 #else
452 {-# INLINE adjust #-}
453 #endif
454
455 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
456 -- a member of the map, the original map is returned.
457 --
458 -- > let f key x = (show key) ++ ":new " ++ x
459 -- > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
460 -- > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
461 -- > adjustWithKey f 7 empty == empty
462
463 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
464 adjustWithKey f = updateWithKey (\k' x' -> Just (f k' x'))
465 #if __GLASGOW_HASKELL__ >= 700
466 {-# INLINABLE adjustWithKey #-}
467 #else
468 {-# INLINE adjustWithKey #-}
469 #endif
470
471 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
472 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
473 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
474 --
475 -- > let f x = if x == "a" then Just "new a" else Nothing
476 -- > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
477 -- > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
478 -- > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
479
480 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
481 update f = updateWithKey (\_ x -> f x)
482 #if __GLASGOW_HASKELL__ >= 700
483 {-# INLINABLE update #-}
484 #else
485 {-# INLINE update #-}
486 #endif
487
488 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
489 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
490 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
491 -- to the new value @y@.
492 --
493 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
494 -- > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
495 -- > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
496 -- > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
497
498 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
499 updateWithKey = go
500 where
501 STRICT_2_OF_3(go)
502 go _ _ Tip = Tip
503 go f k(Bin sx kx x l r) =
504 case compare k kx of
505 LT -> balanceR kx x (go f k l) r
506 GT -> balanceL kx x l (go f k r)
507 EQ -> case f kx x of
508 Just x' -> x' `seq` Bin sx kx x' l r
509 Nothing -> glue l r
510 #if __GLASGOW_HASKELL__ >= 700
511 {-# INLINABLE updateWithKey #-}
512 #else
513 {-# INLINE updateWithKey #-}
514 #endif
515
516 -- | /O(log n)/. Lookup and update. See also 'updateWithKey'.
517 -- The function returns changed value, if it is updated.
518 -- Returns the original key value if the map entry is deleted.
519 --
520 -- > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
521 -- > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
522 -- > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing, fromList [(3, "b"), (5, "a")])
523 -- > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")
524
525 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
526 updateLookupWithKey = go
527 where
528 STRICT_2_OF_3(go)
529 go _ _ Tip = (Nothing,Tip)
530 go f k (Bin sx kx x l r) =
531 case compare k kx of
532 LT -> let (found,l') = go f k l
533 in found `strictPair` balanceR kx x l' r
534 GT -> let (found,r') = go f k r
535 in found `strictPair` balanceL kx x l r'
536 EQ -> case f kx x of
537 Just x' -> x' `seq` (Just x' `strictPair` Bin sx kx x' l r)
538 Nothing -> (Just x,glue l r)
539 #if __GLASGOW_HASKELL__ >= 700
540 {-# INLINABLE updateLookupWithKey #-}
541 #else
542 {-# INLINE updateLookupWithKey #-}
543 #endif
544
545 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
546 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
547 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@.
548 --
549 -- > let f _ = Nothing
550 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
551 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
552 -- >
553 -- > let f _ = Just "c"
554 -- > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
555 -- > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]
556
557 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
558 alter = go
559 where
560 STRICT_2_OF_3(go)
561 go f k Tip = case f Nothing of
562 Nothing -> Tip
563 Just x -> singleton k x
564
565 go f k (Bin sx kx x l r) = case compare k kx of
566 LT -> balance kx x (go f k l) r
567 GT -> balance kx x l (go f k r)
568 EQ -> case f (Just x) of
569 Just x' -> x' `seq` Bin sx kx x' l r
570 Nothing -> glue l r
571 #if __GLASGOW_HASKELL__ >= 700
572 {-# INLINABLE alter #-}
573 #else
574 {-# INLINE alter #-}
575 #endif
576
577 {--------------------------------------------------------------------
578 Indexing
579 --------------------------------------------------------------------}
580
581 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
582 -- invalid index is used.
583 --
584 -- > updateAt (\ _ _ -> Just "x") 0 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "x"), (5, "a")]
585 -- > updateAt (\ _ _ -> Just "x") 1 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "x")]
586 -- > updateAt (\ _ _ -> Just "x") 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
587 -- > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
588 -- > updateAt (\_ _ -> Nothing) 0 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
589 -- > updateAt (\_ _ -> Nothing) 1 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
590 -- > updateAt (\_ _ -> Nothing) 2 (fromList [(5,"a"), (3,"b")]) Error: index out of range
591 -- > updateAt (\_ _ -> Nothing) (-1) (fromList [(5,"a"), (3,"b")]) Error: index out of range
592
593 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
594 updateAt f i t = i `seq`
595 case t of
596 Tip -> error "Map.updateAt: index out of range"
597 Bin sx kx x l r -> case compare i sizeL of
598 LT -> balanceR kx x (updateAt f i l) r
599 GT -> balanceL kx x l (updateAt f (i-sizeL-1) r)
600 EQ -> case f kx x of
601 Just x' -> x' `seq` Bin sx kx x' l r
602 Nothing -> glue l r
603 where
604 sizeL = size l
605
606 {--------------------------------------------------------------------
607 Minimal, Maximal
608 --------------------------------------------------------------------}
609
610 -- | /O(log n)/. Update the value at the minimal key.
611 --
612 -- > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
613 -- > updateMin (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
614
615 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
616 updateMin f m
617 = updateMinWithKey (\_ x -> f x) m
618
619 -- | /O(log n)/. Update the value at the maximal key.
620 --
621 -- > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
622 -- > updateMax (\ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
623
624 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
625 updateMax f m
626 = updateMaxWithKey (\_ x -> f x) m
627
628
629 -- | /O(log n)/. Update the value at the minimal key.
630 --
631 -- > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
632 -- > updateMinWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"
633
634 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
635 updateMinWithKey _ Tip = Tip
636 updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
637 Nothing -> r
638 Just x' -> x' `seq` Bin sx kx x' Tip r
639 updateMinWithKey f (Bin _ kx x l r) = balanceR kx x (updateMinWithKey f l) r
640
641 -- | /O(log n)/. Update the value at the maximal key.
642 --
643 -- > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
644 -- > updateMaxWithKey (\ _ _ -> Nothing) (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
645
646 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
647 updateMaxWithKey _ Tip = Tip
648 updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
649 Nothing -> l
650 Just x' -> x' `seq` Bin sx kx x' l Tip
651 updateMaxWithKey f (Bin _ kx x l r) = balanceL kx x l (updateMaxWithKey f r)
652
653 {--------------------------------------------------------------------
654 Union.
655 --------------------------------------------------------------------}
656
657 -- | The union of a list of maps, with a combining operation:
658 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
659 --
660 -- > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
661 -- > == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]
662
663 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
664 unionsWith f ts
665 = foldlStrict (unionWith f) empty ts
666 #if __GLASGOW_HASKELL__ >= 700
667 {-# INLINABLE unionsWith #-}
668 #endif
669
670 {--------------------------------------------------------------------
671 Union with a combining function
672 --------------------------------------------------------------------}
673 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
674 --
675 -- > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]
676
677 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
678 unionWith f m1 m2
679 = unionWithKey (\_ x y -> f x y) m1 m2
680 #if __GLASGOW_HASKELL__ >= 700
681 {-# INLINABLE unionWith #-}
682 #endif
683
684 -- | /O(n+m)/.
685 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
686 -- Hedge-union is more efficient on (bigset \``union`\` smallset).
687 --
688 -- > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
689 -- > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]
690
691 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
692 unionWithKey _ Tip t2 = t2
693 unionWithKey _ t1 Tip = t1
694 unionWithKey f t1 t2 = hedgeUnionWithKey f NothingS NothingS t1 t2
695 #if __GLASGOW_HASKELL__ >= 700
696 {-# INLINABLE unionWithKey #-}
697 #endif
698
699 hedgeUnionWithKey :: Ord a
700 => (a -> b -> b -> b)
701 -> MaybeS a -> MaybeS a
702 -> Map a b -> Map a b
703 -> Map a b
704 hedgeUnionWithKey _ _ _ t1 Tip
705 = t1
706 hedgeUnionWithKey _ blo bhi Tip (Bin _ kx x l r)
707 = join kx x (filterGt blo l) (filterLt bhi r)
708 hedgeUnionWithKey f blo bhi (Bin _ kx x l r) t2
709 = newx `seq` join kx newx (hedgeUnionWithKey f blo bmi l lt)
710 (hedgeUnionWithKey f bmi bhi r gt)
711 where
712 bmi = JustS kx
713 lt = trim blo bmi t2
714 (found,gt) = trimLookupLo kx bhi t2
715 newx = case found of
716 Nothing -> x
717 Just (_,y) -> f kx x y
718 #if __GLASGOW_HASKELL__ >= 700
719 {-# INLINABLE hedgeUnionWithKey #-}
720 #endif
721
722 {--------------------------------------------------------------------
723 Difference
724 --------------------------------------------------------------------}
725
726 -- | /O(n+m)/. Difference with a combining function.
727 -- When two equal keys are
728 -- encountered, the combining function is applied to the values of these keys.
729 -- If it returns 'Nothing', the element is discarded (proper set difference). If
730 -- it returns (@'Just' y@), the element is updated with a new value @y@.
731 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
732 --
733 -- > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
734 -- > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
735 -- > == singleton 3 "b:B"
736
737 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
738 differenceWith f m1 m2
739 = differenceWithKey (\_ x y -> f x y) m1 m2
740 #if __GLASGOW_HASKELL__ >= 700
741 {-# INLINABLE differenceWith #-}
742 #endif
743
744 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
745 -- encountered, the combining function is applied to the key and both values.
746 -- If it returns 'Nothing', the element is discarded (proper set difference). If
747 -- it returns (@'Just' y@), the element is updated with a new value @y@.
748 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
749 --
750 -- > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
751 -- > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
752 -- > == singleton 3 "3:b|B"
753
754 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
755 differenceWithKey _ Tip _ = Tip
756 differenceWithKey _ t1 Tip = t1
757 differenceWithKey f t1 t2 = hedgeDiffWithKey f NothingS NothingS t1 t2
758 #if __GLASGOW_HASKELL__ >= 700
759 {-# INLINABLE differenceWithKey #-}
760 #endif
761
762 hedgeDiffWithKey :: Ord a
763 => (a -> b -> c -> Maybe b)
764 -> MaybeS a -> MaybeS a
765 -> Map a b -> Map a c
766 -> Map a b
767 hedgeDiffWithKey _ _ _ Tip _
768 = Tip
769 hedgeDiffWithKey _ blo bhi (Bin _ kx x l r) Tip
770 = join kx x (filterGt blo l) (filterLt bhi r)
771 hedgeDiffWithKey f blo bhi t (Bin _ kx x l r)
772 = case found of
773 Nothing -> merge tl tr
774 Just (ky,y) ->
775 case f ky y x of
776 Nothing -> merge tl tr
777 Just z -> z `seq` join ky z tl tr
778 where
779 bmi = JustS kx
780 lt = trim blo bmi t
781 (found,gt) = trimLookupLo kx bhi t
782 tl = hedgeDiffWithKey f blo bmi lt l
783 tr = hedgeDiffWithKey f bmi bhi gt r
784 #if __GLASGOW_HASKELL__ >= 700
785 {-# INLINABLE hedgeDiffWithKey #-}
786 #endif
787
788 {--------------------------------------------------------------------
789 Intersection
790 --------------------------------------------------------------------}
791
792 -- | /O(n+m)/. Intersection with a combining function.
793 --
794 -- > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"
795
796 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
797 intersectionWith f m1 m2
798 = intersectionWithKey (\_ x y -> f x y) m1 m2
799 #if __GLASGOW_HASKELL__ >= 700
800 {-# INLINABLE intersectionWith #-}
801 #endif
802
803 -- | /O(n+m)/. Intersection with a combining function.
804 -- Intersection is more efficient on (bigset \``intersection`\` smallset).
805 --
806 -- > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
807 -- > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"
808
809
810 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
811 intersectionWithKey _ Tip _ = Tip
812 intersectionWithKey _ _ Tip = Tip
813 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
814 if s1 >= s2 then
815 case splitLookupWithKey k2 t1 of
816 (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)
817 (lt, Nothing, gt) -> merge (intersectionWithKey f lt l2) (intersectionWithKey f gt r2)
818 else
819 case splitLookup k1 t2 of
820 (lt, Just x, gt) -> case f k1 x1 x of x' -> x' `seq` join k1 x' (intersectionWithKey f l1 lt) (intersectionWithKey f r1 gt)
821 (lt, Nothing, gt) -> merge (intersectionWithKey f l1 lt) (intersectionWithKey f r1 gt)
822 #if __GLASGOW_HASKELL__ >= 700
823 {-# INLINABLE intersectionWithKey #-}
824 #endif
825
826 {--------------------------------------------------------------------
827 Filter and partition
828 --------------------------------------------------------------------}
829
830 -- | /O(n)/. Map values and collect the 'Just' results.
831 --
832 -- > let f x = if x == "a" then Just "new a" else Nothing
833 -- > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"
834
835 mapMaybe :: (a -> Maybe b) -> Map k a -> Map k b
836 mapMaybe f = mapMaybeWithKey (\_ x -> f x)
837
838 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
839 --
840 -- > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
841 -- > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"
842
843 mapMaybeWithKey :: (k -> a -> Maybe b) -> Map k a -> Map k b
844 mapMaybeWithKey _ Tip = Tip
845 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
846 Just y -> y `seq` join kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
847 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
848
849 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
850 --
851 -- > let f a = if a < "c" then Left a else Right a
852 -- > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
853 -- > == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
854 -- >
855 -- > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
856 -- > == (empty, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
857
858 mapEither :: (a -> Either b c) -> Map k a -> (Map k b, Map k c)
859 mapEither f m
860 = mapEitherWithKey (\_ x -> f x) m
861
862 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
863 --
864 -- > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
865 -- > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
866 -- > == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
867 -- >
868 -- > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
869 -- > == (empty, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])
870
871 mapEitherWithKey :: (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
872 mapEitherWithKey _ Tip = (Tip, Tip)
873 mapEitherWithKey f (Bin _ kx x l r) = case f kx x of
874 Left y -> y `seq` (join kx y l1 r1 `strictPair` merge l2 r2)
875 Right z -> z `seq` (merge l1 r1 `strictPair` join kx z l2 r2)
876 where
877 (l1,l2) = mapEitherWithKey f l
878 (r1,r2) = mapEitherWithKey f r
879
880 {--------------------------------------------------------------------
881 Mapping
882 --------------------------------------------------------------------}
883 -- | /O(n)/. Map a function over all values in the map.
884 --
885 -- > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]
886
887 map :: (a -> b) -> Map k a -> Map k b
888 map f = mapWithKey (\_ x -> f x)
889
890 -- | /O(n)/. Map a function over all values in the map.
891 --
892 -- > let f key x = (show key) ++ ":" ++ x
893 -- > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]
894
895 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
896 mapWithKey _ Tip = Tip
897 mapWithKey f (Bin sx kx x l r) = let x' = f kx x
898 in x' `seq` Bin sx kx x' (mapWithKey f l) (mapWithKey f r)
899
900 -- | /O(n)/. The function 'mapAccum' threads an accumulating
901 -- argument through the map in ascending order of keys.
902 --
903 -- > let f a b = (a ++ b, b ++ "X")
904 -- > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])
905
906 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
907 mapAccum f a m
908 = mapAccumWithKey (\a' _ x' -> f a' x') a m
909
910 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
911 -- argument through the map in ascending order of keys.
912 --
913 -- > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
914 -- > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])
915
916 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
917 mapAccumWithKey f a t
918 = mapAccumL f a t
919
920 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
921 -- argument through the map in ascending order of keys.
922 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
923 mapAccumL _ a Tip = (a,Tip)
924 mapAccumL f a (Bin sx kx x l r) =
925 let (a1,l') = mapAccumL f a l
926 (a2,x') = f a1 kx x
927 (a3,r') = mapAccumL f a2 r
928 in x' `seq` (a3,Bin sx kx x' l' r')
929
930 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
931 -- argument through the map in descending order of keys.
932 mapAccumRWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
933 mapAccumRWithKey _ a Tip = (a,Tip)
934 mapAccumRWithKey f a (Bin sx kx x l r) =
935 let (a1,r') = mapAccumRWithKey f a r
936 (a2,x') = f a1 kx x
937 (a3,l') = mapAccumRWithKey f a2 l
938 in x' `seq` (a3,Bin sx kx x' l' r')
939
940 -- | /O(n*log n)/.
941 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
942 --
943 -- The size of the result may be smaller if @f@ maps two or more distinct
944 -- keys to the same new key. In this case the associated values will be
945 -- combined using @c@.
946 --
947 -- > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
948 -- > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"
949
950 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
951 mapKeysWith c f = fromListWith c . foldrWithKey (\k x xs -> (f k, x) : xs) []
952 #if __GLASGOW_HASKELL__ >= 700
953 {-# INLINABLE mapKeysWith #-}
954 #endif
955
956 {--------------------------------------------------------------------
957 Lists
958 use [foldlStrict] to reduce demand on the control-stack
959 --------------------------------------------------------------------}
960 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
961 -- If the list contains more than one value for the same key, the last value
962 -- for the key is retained.
963 --
964 -- > fromList [] == empty
965 -- > fromList [(5,"a"), (3,"b"), (5, "c")] == fromList [(5,"c"), (3,"b")]
966 -- > fromList [(5,"c"), (3,"b"), (5, "a")] == fromList [(5,"a"), (3,"b")]
967
968 fromList :: Ord k => [(k,a)] -> Map k a
969 fromList xs
970 = foldlStrict ins empty xs
971 where
972 ins t (k,x) = insert k x t
973 #if __GLASGOW_HASKELL__ >= 700
974 {-# INLINABLE fromList #-}
975 #endif
976
977 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
978 --
979 -- > fromListWith (++) [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "ab"), (5, "aba")]
980 -- > fromListWith (++) [] == empty
981
982 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
983 fromListWith f xs
984 = fromListWithKey (\_ x y -> f x y) xs
985 #if __GLASGOW_HASKELL__ >= 700
986 {-# INLINABLE fromListWith #-}
987 #endif
988
989 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
990 --
991 -- > let f k a1 a2 = (show k) ++ a1 ++ a2
992 -- > fromListWithKey f [(5,"a"), (5,"b"), (3,"b"), (3,"a"), (5,"a")] == fromList [(3, "3ab"), (5, "5a5ba")]
993 -- > fromListWithKey f [] == empty
994
995 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
996 fromListWithKey f xs
997 = foldlStrict ins empty xs
998 where
999 ins t (k,x) = insertWithKey f k x t
1000 #if __GLASGOW_HASKELL__ >= 700
1001 {-# INLINABLE fromListWithKey #-}
1002 #endif
1003
1004 {--------------------------------------------------------------------
1005 Building trees from ascending/descending lists can be done in linear time.
1006
1007 Note that if [xs] is ascending that:
1008 fromAscList xs == fromList xs
1009 fromAscListWith f xs == fromListWith f xs
1010 --------------------------------------------------------------------}
1011 -- | /O(n)/. Build a map from an ascending list in linear time.
1012 -- /The precondition (input list is ascending) is not checked./
1013 --
1014 -- > fromAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1015 -- > fromAscList [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "b")]
1016 -- > valid (fromAscList [(3,"b"), (5,"a"), (5,"b")]) == True
1017 -- > valid (fromAscList [(5,"a"), (3,"b"), (5,"b")]) == False
1018
1019 fromAscList :: Eq k => [(k,a)] -> Map k a
1020 fromAscList xs
1021 = fromAscListWithKey (\_ x _ -> x) xs
1022 #if __GLASGOW_HASKELL__ >= 700
1023 {-# INLINABLE fromAscList #-}
1024 #endif
1025
1026 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1027 -- /The precondition (input list is ascending) is not checked./
1028 --
1029 -- > fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")] == fromList [(3, "b"), (5, "ba")]
1030 -- > valid (fromAscListWith (++) [(3,"b"), (5,"a"), (5,"b")]) == True
1031 -- > valid (fromAscListWith (++) [(5,"a"), (3,"b"), (5,"b")]) == False
1032
1033 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1034 fromAscListWith f xs
1035 = fromAscListWithKey (\_ x y -> f x y) xs
1036 #if __GLASGOW_HASKELL__ >= 700
1037 {-# INLINABLE fromAscListWith #-}
1038 #endif
1039
1040 -- | /O(n)/. Build a map from an ascending list in linear time with a
1041 -- combining function for equal keys.
1042 -- /The precondition (input list is ascending) is not checked./
1043 --
1044 -- > let f k a1 a2 = (show k) ++ ":" ++ a1 ++ a2
1045 -- > fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")] == fromList [(3, "b"), (5, "5:b5:ba")]
1046 -- > valid (fromAscListWithKey f [(3,"b"), (5,"a"), (5,"b"), (5,"b")]) == True
1047 -- > valid (fromAscListWithKey f [(5,"a"), (3,"b"), (5,"b"), (5,"b")]) == False
1048
1049 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1050 fromAscListWithKey f xs
1051 = fromDistinctAscList (combineEq f xs)
1052 where
1053 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1054 combineEq _ xs'
1055 = case xs' of
1056 [] -> []
1057 [x] -> [x]
1058 (x:xx) -> combineEq' x xx
1059
1060 combineEq' z [] = [z]
1061 combineEq' z@(kz,zz) (x@(kx,xx):xs')
1062 | kx==kz = let yy = f kx xx zz in yy `seq` combineEq' (kx,yy) xs'
1063 | otherwise = z:combineEq' x xs'
1064 #if __GLASGOW_HASKELL__ >= 700
1065 {-# INLINABLE fromAscListWithKey #-}
1066 #endif
1067
1068 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1069 -- /The precondition is not checked./
1070 --
1071 -- > fromDistinctAscList [(3,"b"), (5,"a")] == fromList [(3, "b"), (5, "a")]
1072 -- > valid (fromDistinctAscList [(3,"b"), (5,"a")]) == True
1073 -- > valid (fromDistinctAscList [(3,"b"), (5,"a"), (5,"b")]) == False
1074
1075 fromDistinctAscList :: [(k,a)] -> Map k a
1076 fromDistinctAscList xs
1077 = create const (length xs) xs
1078 where
1079 -- 1) use continuations so that we use heap space instead of stack space.
1080 -- 2) special case for n==5 to create bushier trees.
1081 create c 0 xs' = c Tip xs'
1082 create c 5 xs' = case xs' of
1083 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1084 -> x1 `seq` x2 `seq` x3 `seq` x4 `seq` x5 `seq`
1085 c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3))
1086 (singleton k5 x5)) xx
1087 _ -> error "fromDistinctAscList create"
1088 create c n xs' = seq nr $ create (createR nr c) nl xs'
1089 where nl = n `div` 2
1090 nr = n - nl - 1
1091
1092 createR n c l ((k,x):ys) = x `seq` create (createB l k x c) n ys
1093 createR _ _ _ [] = error "fromDistinctAscList createR []"
1094 createB l k x c r zs = x `seq` c (bin k x l r) zs