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