1 {-# OPTIONS -cpp -fglasgow-exts -fno-bang-patterns #-}
2 -----------------------------------------------------------------------------
3 -- Module : Data.IntMap
4 -- Copyright : (c) Daan Leijen 2002
6 -- Maintainer : libraries@haskell.org
7 -- Stability : provisional
8 -- Portability : portable
10 -- An efficient implementation of maps from integer keys to values.
12 -- This module is intended to be imported @qualified@, to avoid name
13 -- clashes with "Prelude" functions. eg.
15 -- > import Data.IntMap as Map
17 -- The implementation is based on /big-endian patricia trees/. This data
18 -- structure performs especially well on binary operations like 'union'
19 -- and 'intersection'. However, my benchmarks show that it is also
20 -- (much) faster on insertions and deletions when compared to a generic
21 -- size-balanced map implementation (see "Data.Map" and "Data.FiniteMap").
23 -- * Chris Okasaki and Andy Gill, \"/Fast Mergeable Integer Maps/\",
24 -- Workshop on ML, September 1998, pages 77-86,
25 -- <http://www.cse.ogi.edu/~andy/pub/finite.htm>
27 -- * D.R. Morrison, \"/PATRICIA -- Practical Algorithm To Retrieve
28 -- Information Coded In Alphanumeric/\", Journal of the ACM, 15(4),
29 -- October 1968, pages 514-534.
31 -- Many operations have a worst-case complexity of /O(min(n,W))/.
32 -- This means that the operation can become linear in the number of
33 -- elements with a maximum of /W/ -- the number of bits in an 'Int'
35 -----------------------------------------------------------------------------
39 IntMap, Key -- instance Eq,Show
58 , insertWith, insertWithKey, insertLookupWithKey
115 , fromDistinctAscList
127 , isSubmapOf, isSubmapOfBy
128 , isProperSubmapOf, isProperSubmapOfBy
136 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
139 import qualified Data.IntSet as IntSet
140 import Data.Monoid (Monoid(..))
142 import Data.Foldable (Foldable(foldMap))
146 import qualified Prelude
147 import Debug.QuickCheck
148 import List (nub,sort)
149 import qualified List
152 #if __GLASGOW_HASKELL__
154 import Data.Generics.Basics
155 import Data.Generics.Instances
158 #if __GLASGOW_HASKELL__ >= 503
160 import GHC.Exts ( Word(..), Int(..), shiftRL# )
161 #elif __GLASGOW_HASKELL__
163 import GlaExts ( Word(..), Int(..), shiftRL# )
168 infixl 9 \\{-This comment teaches CPP correct behaviour -}
170 -- A "Nat" is a natural machine word (an unsigned Int)
173 natFromInt :: Key -> Nat
174 natFromInt i = fromIntegral i
176 intFromNat :: Nat -> Key
177 intFromNat w = fromIntegral w
179 shiftRL :: Nat -> Key -> Nat
180 #if __GLASGOW_HASKELL__
181 {--------------------------------------------------------------------
182 GHC: use unboxing to get @shiftRL@ inlined.
183 --------------------------------------------------------------------}
184 shiftRL (W# x) (I# i)
187 shiftRL x i = shiftR x i
190 {--------------------------------------------------------------------
192 --------------------------------------------------------------------}
194 -- | /O(min(n,W))/. Find the value at a key.
195 -- Calls 'error' when the element can not be found.
197 (!) :: IntMap a -> Key -> a
200 -- | /O(n+m)/. See 'difference'.
201 (\\) :: IntMap a -> IntMap b -> IntMap a
202 m1 \\ m2 = difference m1 m2
204 {--------------------------------------------------------------------
206 --------------------------------------------------------------------}
207 -- | A map of integers to values @a@.
209 | Tip {-# UNPACK #-} !Key a
210 | Bin {-# UNPACK #-} !Prefix {-# UNPACK #-} !Mask !(IntMap a) !(IntMap a)
216 instance Monoid (IntMap a) where
221 instance Foldable IntMap where
222 foldMap f Nil = mempty
223 foldMap f (Tip _k v) = f v
224 foldMap f (Bin _ _ l r) = foldMap f l `mappend` foldMap f r
226 #if __GLASGOW_HASKELL__
228 {--------------------------------------------------------------------
230 --------------------------------------------------------------------}
232 -- This instance preserves data abstraction at the cost of inefficiency.
233 -- We omit reflection services for the sake of data abstraction.
235 instance Data a => Data (IntMap a) where
236 gfoldl f z im = z fromList `f` (toList im)
237 toConstr _ = error "toConstr"
238 gunfold _ _ = error "gunfold"
239 dataTypeOf _ = mkNorepType "Data.IntMap.IntMap"
240 dataCast1 f = gcast1 f
244 {--------------------------------------------------------------------
246 --------------------------------------------------------------------}
247 -- | /O(1)/. Is the map empty?
248 null :: IntMap a -> Bool
252 -- | /O(n)/. Number of elements in the map.
253 size :: IntMap a -> Int
256 Bin p m l r -> size l + size r
260 -- | /O(min(n,W))/. Is the key a member of the map?
261 member :: Key -> IntMap a -> Bool
267 -- | /O(log n)/. Is the key not a member of the map?
268 notMember :: Key -> IntMap a -> Bool
269 notMember k m = not $ member k m
271 -- | /O(min(n,W))/. Lookup the value at a key in the map.
272 lookup :: Key -> IntMap a -> Maybe a
274 = let nk = natFromInt k in seq nk (lookupN nk t)
276 lookupN :: Nat -> IntMap a -> Maybe a
280 | zeroN k (natFromInt m) -> lookupN k l
281 | otherwise -> lookupN k r
283 | (k == natFromInt kx) -> Just x
284 | otherwise -> Nothing
287 find' :: Key -> IntMap a -> a
290 Nothing -> error ("IntMap.find: key " ++ show k ++ " is not an element of the map")
294 -- | /O(min(n,W))/. The expression @('findWithDefault' def k map)@
295 -- returns the value at key @k@ or returns @def@ when the key is not an
296 -- element of the map.
297 findWithDefault :: a -> Key -> IntMap a -> a
298 findWithDefault def k m
303 {--------------------------------------------------------------------
305 --------------------------------------------------------------------}
306 -- | /O(1)/. The empty map.
311 -- | /O(1)/. A map of one element.
312 singleton :: Key -> a -> IntMap a
316 {--------------------------------------------------------------------
318 --------------------------------------------------------------------}
319 -- | /O(min(n,W))/. Insert a new key\/value pair in the map.
320 -- If the key is already present in the map, the associated value is
321 -- replaced with the supplied value, i.e. 'insert' is equivalent to
322 -- @'insertWith' 'const'@.
323 insert :: Key -> a -> IntMap a -> IntMap a
327 | nomatch k p m -> join k (Tip k x) p t
328 | zero k m -> Bin p m (insert k x l) r
329 | otherwise -> Bin p m l (insert k x r)
332 | otherwise -> join k (Tip k x) ky t
335 -- right-biased insertion, used by 'union'
336 -- | /O(min(n,W))/. Insert with a combining function.
337 -- @'insertWith' f key value mp@
338 -- will insert the pair (key, value) into @mp@ if key does
339 -- not exist in the map. If the key does exist, the function will
340 -- insert @f new_value old_value@.
341 insertWith :: (a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
343 = insertWithKey (\k x y -> f x y) k x t
345 -- | /O(min(n,W))/. Insert with a combining function.
346 -- @'insertWithKey' f key value mp@
347 -- will insert the pair (key, value) into @mp@ if key does
348 -- not exist in the map. If the key does exist, the function will
349 -- insert @f key new_value old_value@.
350 insertWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
351 insertWithKey f k x t
354 | nomatch k p m -> join k (Tip k x) p t
355 | zero k m -> Bin p m (insertWithKey f k x l) r
356 | otherwise -> Bin p m l (insertWithKey f k x r)
358 | k==ky -> Tip k (f k x y)
359 | otherwise -> join k (Tip k x) ky t
363 -- | /O(min(n,W))/. The expression (@'insertLookupWithKey' f k x map@)
364 -- is a pair where the first element is equal to (@'lookup' k map@)
365 -- and the second element equal to (@'insertWithKey' f k x map@).
366 insertLookupWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> (Maybe a, IntMap a)
367 insertLookupWithKey f k x t
370 | nomatch k p m -> (Nothing,join k (Tip k x) p t)
371 | zero k m -> let (found,l') = insertLookupWithKey f k x l in (found,Bin p m l' r)
372 | otherwise -> let (found,r') = insertLookupWithKey f k x r in (found,Bin p m l r')
374 | k==ky -> (Just y,Tip k (f k x y))
375 | otherwise -> (Nothing,join k (Tip k x) ky t)
376 Nil -> (Nothing,Tip k x)
379 {--------------------------------------------------------------------
381 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
382 --------------------------------------------------------------------}
383 -- | /O(min(n,W))/. Delete a key and its value from the map. When the key is not
384 -- a member of the map, the original map is returned.
385 delete :: Key -> IntMap a -> IntMap a
390 | zero k m -> bin p m (delete k l) r
391 | otherwise -> bin p m l (delete k r)
397 -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
398 -- a member of the map, the original map is returned.
399 adjust :: (a -> a) -> Key -> IntMap a -> IntMap a
401 = adjustWithKey (\k x -> f x) k m
403 -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
404 -- a member of the map, the original map is returned.
405 adjustWithKey :: (Key -> a -> a) -> Key -> IntMap a -> IntMap a
407 = updateWithKey (\k x -> Just (f k x)) k m
409 -- | /O(min(n,W))/. The expression (@'update' f k map@) updates the value @x@
410 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
411 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
412 update :: (a -> Maybe a) -> Key -> IntMap a -> IntMap a
414 = updateWithKey (\k x -> f x) k m
416 -- | /O(min(n,W))/. The expression (@'update' f k map@) updates the value @x@
417 -- at @k@ (if it is in the map). If (@f k x@) is 'Nothing', the element is
418 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
419 updateWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> IntMap a
424 | zero k m -> bin p m (updateWithKey f k l) r
425 | otherwise -> bin p m l (updateWithKey f k r)
427 | k==ky -> case (f k y) of
433 -- | /O(min(n,W))/. Lookup and update.
434 updateLookupWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> (Maybe a,IntMap a)
435 updateLookupWithKey f k t
438 | nomatch k p m -> (Nothing,t)
439 | zero k m -> let (found,l') = updateLookupWithKey f k l in (found,bin p m l' r)
440 | otherwise -> let (found,r') = updateLookupWithKey f k r in (found,bin p m l r')
442 | k==ky -> case (f k y) of
443 Just y' -> (Just y,Tip ky y')
444 Nothing -> (Just y,Nil)
445 | otherwise -> (Nothing,t)
449 {--------------------------------------------------------------------
451 --------------------------------------------------------------------}
452 -- | The union of a list of maps.
453 unions :: [IntMap a] -> IntMap a
455 = foldlStrict union empty xs
457 -- | The union of a list of maps, with a combining operation
458 unionsWith :: (a->a->a) -> [IntMap a] -> IntMap a
460 = foldlStrict (unionWith f) empty ts
462 -- | /O(n+m)/. The (left-biased) union of two maps.
463 -- It prefers the first map when duplicate keys are encountered,
464 -- i.e. (@'union' == 'unionWith' 'const'@).
465 union :: IntMap a -> IntMap a -> IntMap a
466 union t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
467 | shorter m1 m2 = union1
468 | shorter m2 m1 = union2
469 | p1 == p2 = Bin p1 m1 (union l1 l2) (union r1 r2)
470 | otherwise = join p1 t1 p2 t2
472 union1 | nomatch p2 p1 m1 = join p1 t1 p2 t2
473 | zero p2 m1 = Bin p1 m1 (union l1 t2) r1
474 | otherwise = Bin p1 m1 l1 (union r1 t2)
476 union2 | nomatch p1 p2 m2 = join p1 t1 p2 t2
477 | zero p1 m2 = Bin p2 m2 (union t1 l2) r2
478 | otherwise = Bin p2 m2 l2 (union t1 r2)
480 union (Tip k x) t = insert k x t
481 union t (Tip k x) = insertWith (\x y -> y) k x t -- right bias
485 -- | /O(n+m)/. The union with a combining function.
486 unionWith :: (a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
488 = unionWithKey (\k x y -> f x y) m1 m2
490 -- | /O(n+m)/. The union with a combining function.
491 unionWithKey :: (Key -> a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
492 unionWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
493 | shorter m1 m2 = union1
494 | shorter m2 m1 = union2
495 | p1 == p2 = Bin p1 m1 (unionWithKey f l1 l2) (unionWithKey f r1 r2)
496 | otherwise = join p1 t1 p2 t2
498 union1 | nomatch p2 p1 m1 = join p1 t1 p2 t2
499 | zero p2 m1 = Bin p1 m1 (unionWithKey f l1 t2) r1
500 | otherwise = Bin p1 m1 l1 (unionWithKey f r1 t2)
502 union2 | nomatch p1 p2 m2 = join p1 t1 p2 t2
503 | zero p1 m2 = Bin p2 m2 (unionWithKey f t1 l2) r2
504 | otherwise = Bin p2 m2 l2 (unionWithKey f t1 r2)
506 unionWithKey f (Tip k x) t = insertWithKey f k x t
507 unionWithKey f t (Tip k x) = insertWithKey (\k x y -> f k y x) k x t -- right bias
508 unionWithKey f Nil t = t
509 unionWithKey f t Nil = t
511 {--------------------------------------------------------------------
513 --------------------------------------------------------------------}
514 -- | /O(n+m)/. Difference between two maps (based on keys).
515 difference :: IntMap a -> IntMap b -> IntMap a
516 difference t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
517 | shorter m1 m2 = difference1
518 | shorter m2 m1 = difference2
519 | p1 == p2 = bin p1 m1 (difference l1 l2) (difference r1 r2)
522 difference1 | nomatch p2 p1 m1 = t1
523 | zero p2 m1 = bin p1 m1 (difference l1 t2) r1
524 | otherwise = bin p1 m1 l1 (difference r1 t2)
526 difference2 | nomatch p1 p2 m2 = t1
527 | zero p1 m2 = difference t1 l2
528 | otherwise = difference t1 r2
530 difference t1@(Tip k x) t2
534 difference Nil t = Nil
535 difference t (Tip k x) = delete k t
538 -- | /O(n+m)/. Difference with a combining function.
539 differenceWith :: (a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
540 differenceWith f m1 m2
541 = differenceWithKey (\k x y -> f x y) m1 m2
543 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
544 -- encountered, the combining function is applied to the key and both values.
545 -- If it returns 'Nothing', the element is discarded (proper set difference).
546 -- If it returns (@'Just' y@), the element is updated with a new value @y@.
547 differenceWithKey :: (Key -> a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
548 differenceWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
549 | shorter m1 m2 = difference1
550 | shorter m2 m1 = difference2
551 | p1 == p2 = bin p1 m1 (differenceWithKey f l1 l2) (differenceWithKey f r1 r2)
554 difference1 | nomatch p2 p1 m1 = t1
555 | zero p2 m1 = bin p1 m1 (differenceWithKey f l1 t2) r1
556 | otherwise = bin p1 m1 l1 (differenceWithKey f r1 t2)
558 difference2 | nomatch p1 p2 m2 = t1
559 | zero p1 m2 = differenceWithKey f t1 l2
560 | otherwise = differenceWithKey f t1 r2
562 differenceWithKey f t1@(Tip k x) t2
563 = case lookup k t2 of
564 Just y -> case f k x y of
569 differenceWithKey f Nil t = Nil
570 differenceWithKey f t (Tip k y) = updateWithKey (\k x -> f k x y) k t
571 differenceWithKey f t Nil = t
574 {--------------------------------------------------------------------
576 --------------------------------------------------------------------}
577 -- | /O(n+m)/. The (left-biased) intersection of two maps (based on keys).
578 intersection :: IntMap a -> IntMap b -> IntMap a
579 intersection t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
580 | shorter m1 m2 = intersection1
581 | shorter m2 m1 = intersection2
582 | p1 == p2 = bin p1 m1 (intersection l1 l2) (intersection r1 r2)
585 intersection1 | nomatch p2 p1 m1 = Nil
586 | zero p2 m1 = intersection l1 t2
587 | otherwise = intersection r1 t2
589 intersection2 | nomatch p1 p2 m2 = Nil
590 | zero p1 m2 = intersection t1 l2
591 | otherwise = intersection t1 r2
593 intersection t1@(Tip k x) t2
596 intersection t (Tip k x)
600 intersection Nil t = Nil
601 intersection t Nil = Nil
603 -- | /O(n+m)/. The intersection with a combining function.
604 intersectionWith :: (a -> b -> a) -> IntMap a -> IntMap b -> IntMap a
605 intersectionWith f m1 m2
606 = intersectionWithKey (\k x y -> f x y) m1 m2
608 -- | /O(n+m)/. The intersection with a combining function.
609 intersectionWithKey :: (Key -> a -> b -> a) -> IntMap a -> IntMap b -> IntMap a
610 intersectionWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
611 | shorter m1 m2 = intersection1
612 | shorter m2 m1 = intersection2
613 | p1 == p2 = bin p1 m1 (intersectionWithKey f l1 l2) (intersectionWithKey f r1 r2)
616 intersection1 | nomatch p2 p1 m1 = Nil
617 | zero p2 m1 = intersectionWithKey f l1 t2
618 | otherwise = intersectionWithKey f r1 t2
620 intersection2 | nomatch p1 p2 m2 = Nil
621 | zero p1 m2 = intersectionWithKey f t1 l2
622 | otherwise = intersectionWithKey f t1 r2
624 intersectionWithKey f t1@(Tip k x) t2
625 = case lookup k t2 of
626 Just y -> Tip k (f k x y)
628 intersectionWithKey f t1 (Tip k y)
629 = case lookup k t1 of
630 Just x -> Tip k (f k x y)
632 intersectionWithKey f Nil t = Nil
633 intersectionWithKey f t Nil = Nil
636 {--------------------------------------------------------------------
638 --------------------------------------------------------------------}
639 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
640 -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
641 isProperSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
642 isProperSubmapOf m1 m2
643 = isProperSubmapOfBy (==) m1 m2
645 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
646 The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
647 @m1@ and @m2@ are not equal,
648 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
649 applied to their respective values. For example, the following
650 expressions are all 'True':
652 > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
653 > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
655 But the following are all 'False':
657 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
658 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
659 > isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
661 isProperSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
662 isProperSubmapOfBy pred t1 t2
663 = case submapCmp pred t1 t2 of
667 submapCmp pred t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
669 | shorter m2 m1 = submapCmpLt
670 | p1 == p2 = submapCmpEq
671 | otherwise = GT -- disjoint
673 submapCmpLt | nomatch p1 p2 m2 = GT
674 | zero p1 m2 = submapCmp pred t1 l2
675 | otherwise = submapCmp pred t1 r2
676 submapCmpEq = case (submapCmp pred l1 l2, submapCmp pred r1 r2) of
682 submapCmp pred (Bin p m l r) t = GT
683 submapCmp pred (Tip kx x) (Tip ky y)
684 | (kx == ky) && pred x y = EQ
685 | otherwise = GT -- disjoint
686 submapCmp pred (Tip k x) t
688 Just y | pred x y -> LT
689 other -> GT -- disjoint
690 submapCmp pred Nil Nil = EQ
691 submapCmp pred Nil t = LT
693 -- | /O(n+m)/. Is this a submap?
694 -- Defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
695 isSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
697 = isSubmapOfBy (==) m1 m2
700 The expression (@'isSubmapOfBy' f m1 m2@) returns 'True' if
701 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
702 applied to their respective values. For example, the following
703 expressions are all 'True':
705 > isSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
706 > isSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
707 > isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
709 But the following are all 'False':
711 > isSubmapOfBy (==) (fromList [(1,2)]) (fromList [(1,1),(2,2)])
712 > isSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
713 > isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
716 isSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
717 isSubmapOfBy pred t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
718 | shorter m1 m2 = False
719 | shorter m2 m1 = match p1 p2 m2 && (if zero p1 m2 then isSubmapOfBy pred t1 l2
720 else isSubmapOfBy pred t1 r2)
721 | otherwise = (p1==p2) && isSubmapOfBy pred l1 l2 && isSubmapOfBy pred r1 r2
722 isSubmapOfBy pred (Bin p m l r) t = False
723 isSubmapOfBy pred (Tip k x) t = case lookup k t of
726 isSubmapOfBy pred Nil t = True
728 {--------------------------------------------------------------------
730 --------------------------------------------------------------------}
731 -- | /O(n)/. Map a function over all values in the map.
732 map :: (a -> b) -> IntMap a -> IntMap b
734 = mapWithKey (\k x -> f x) m
736 -- | /O(n)/. Map a function over all values in the map.
737 mapWithKey :: (Key -> a -> b) -> IntMap a -> IntMap b
740 Bin p m l r -> Bin p m (mapWithKey f l) (mapWithKey f r)
741 Tip k x -> Tip k (f k x)
744 -- | /O(n)/. The function @'mapAccum'@ threads an accumulating
745 -- argument through the map in ascending order of keys.
746 mapAccum :: (a -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
748 = mapAccumWithKey (\a k x -> f a x) a m
750 -- | /O(n)/. The function @'mapAccumWithKey'@ threads an accumulating
751 -- argument through the map in ascending order of keys.
752 mapAccumWithKey :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
753 mapAccumWithKey f a t
756 -- | /O(n)/. The function @'mapAccumL'@ threads an accumulating
757 -- argument through the map in ascending order of keys.
758 mapAccumL :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
761 Bin p m l r -> let (a1,l') = mapAccumL f a l
762 (a2,r') = mapAccumL f a1 r
763 in (a2,Bin p m l' r')
764 Tip k x -> let (a',x') = f a k x in (a',Tip k x')
768 -- | /O(n)/. The function @'mapAccumR'@ threads an accumulating
769 -- argument throught the map in descending order of keys.
770 mapAccumR :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
773 Bin p m l r -> let (a1,r') = mapAccumR f a r
774 (a2,l') = mapAccumR f a1 l
775 in (a2,Bin p m l' r')
776 Tip k x -> let (a',x') = f a k x in (a',Tip k x')
779 {--------------------------------------------------------------------
781 --------------------------------------------------------------------}
782 -- | /O(n)/. Filter all values that satisfy some predicate.
783 filter :: (a -> Bool) -> IntMap a -> IntMap a
785 = filterWithKey (\k x -> p x) m
787 -- | /O(n)/. Filter all keys\/values that satisfy some predicate.
788 filterWithKey :: (Key -> a -> Bool) -> IntMap a -> IntMap a
792 -> bin p m (filterWithKey pred l) (filterWithKey pred r)
798 -- | /O(n)/. partition the map according to some predicate. The first
799 -- map contains all elements that satisfy the predicate, the second all
800 -- elements that fail the predicate. See also 'split'.
801 partition :: (a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
803 = partitionWithKey (\k x -> p x) m
805 -- | /O(n)/. partition the map according to some predicate. The first
806 -- map contains all elements that satisfy the predicate, the second all
807 -- elements that fail the predicate. See also 'split'.
808 partitionWithKey :: (Key -> a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
809 partitionWithKey pred t
812 -> let (l1,l2) = partitionWithKey pred l
813 (r1,r2) = partitionWithKey pred r
814 in (bin p m l1 r1, bin p m l2 r2)
816 | pred k x -> (t,Nil)
817 | otherwise -> (Nil,t)
821 -- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@
822 -- where all keys in @map1@ are lower than @k@ and all keys in
823 -- @map2@ larger than @k@. Any key equal to @k@ is found in neither @map1@ nor @map2@.
824 split :: Key -> IntMap a -> (IntMap a,IntMap a)
828 | m < 0 -> (if k >= 0 -- handle negative numbers.
829 then let (lt,gt) = split' k l in (union r lt, gt)
830 else let (lt,gt) = split' k r in (lt, union gt l))
831 | otherwise -> split' k t
835 | otherwise -> (Nil,Nil)
838 split' :: Key -> IntMap a -> (IntMap a,IntMap a)
842 | nomatch k p m -> if k>p then (t,Nil) else (Nil,t)
843 | zero k m -> let (lt,gt) = split k l in (lt,union gt r)
844 | otherwise -> let (lt,gt) = split k r in (union l lt,gt)
848 | otherwise -> (Nil,Nil)
851 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
852 -- key was found in the original map.
853 splitLookup :: Key -> IntMap a -> (IntMap a,Maybe a,IntMap a)
857 | m < 0 -> (if k >= 0 -- handle negative numbers.
858 then let (lt,found,gt) = splitLookup' k l in (union r lt,found, gt)
859 else let (lt,found,gt) = splitLookup' k r in (lt,found, union gt l))
860 | otherwise -> splitLookup' k t
862 | k>ky -> (t,Nothing,Nil)
863 | k<ky -> (Nil,Nothing,t)
864 | otherwise -> (Nil,Just y,Nil)
865 Nil -> (Nil,Nothing,Nil)
867 splitLookup' :: Key -> IntMap a -> (IntMap a,Maybe a,IntMap a)
871 | nomatch k p m -> if k>p then (t,Nothing,Nil) else (Nil,Nothing,t)
872 | zero k m -> let (lt,found,gt) = splitLookup k l in (lt,found,union gt r)
873 | otherwise -> let (lt,found,gt) = splitLookup k r in (union l lt,found,gt)
875 | k>ky -> (t,Nothing,Nil)
876 | k<ky -> (Nil,Nothing,t)
877 | otherwise -> (Nil,Just y,Nil)
878 Nil -> (Nil,Nothing,Nil)
880 {--------------------------------------------------------------------
882 --------------------------------------------------------------------}
883 -- | /O(n)/. Fold the values in the map, such that
884 -- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
887 -- > elems map = fold (:) [] map
889 fold :: (a -> b -> b) -> b -> IntMap a -> b
891 = foldWithKey (\k x y -> f x y) z t
893 -- | /O(n)/. Fold the keys and values in the map, such that
894 -- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
897 -- > keys map = foldWithKey (\k x ks -> k:ks) [] map
899 foldWithKey :: (Key -> a -> b -> b) -> b -> IntMap a -> b
903 foldr :: (Key -> a -> b -> b) -> b -> IntMap a -> b
906 Bin 0 m l r | m < 0 -> foldr' f (foldr' f z l) r -- put negative numbers before.
907 Bin _ _ _ _ -> foldr' f z t
911 foldr' :: (Key -> a -> b -> b) -> b -> IntMap a -> b
914 Bin p m l r -> foldr' f (foldr' f z r) l
920 {--------------------------------------------------------------------
922 --------------------------------------------------------------------}
924 -- Return all elements of the map in the ascending order of their keys.
925 elems :: IntMap a -> [a]
927 = foldWithKey (\k x xs -> x:xs) [] m
929 -- | /O(n)/. Return all keys of the map in ascending order.
930 keys :: IntMap a -> [Key]
932 = foldWithKey (\k x ks -> k:ks) [] m
934 -- | /O(n*min(n,W))/. The set of all keys of the map.
935 keysSet :: IntMap a -> IntSet.IntSet
936 keysSet m = IntSet.fromDistinctAscList (keys m)
939 -- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
940 assocs :: IntMap a -> [(Key,a)]
945 {--------------------------------------------------------------------
947 --------------------------------------------------------------------}
948 -- | /O(n)/. Convert the map to a list of key\/value pairs.
949 toList :: IntMap a -> [(Key,a)]
951 = foldWithKey (\k x xs -> (k,x):xs) [] t
953 -- | /O(n)/. Convert the map to a list of key\/value pairs where the
954 -- keys are in ascending order.
955 toAscList :: IntMap a -> [(Key,a)]
957 = -- NOTE: the following algorithm only works for big-endian trees
958 let (pos,neg) = span (\(k,x) -> k >=0) (foldr (\k x xs -> (k,x):xs) [] t) in neg ++ pos
960 -- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs.
961 fromList :: [(Key,a)] -> IntMap a
963 = foldlStrict ins empty xs
965 ins t (k,x) = insert k x t
967 -- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
968 fromListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a
970 = fromListWithKey (\k x y -> f x y) xs
972 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs with a combining function. See also fromAscListWithKey'.
973 fromListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a
975 = foldlStrict ins empty xs
977 ins t (k,x) = insertWithKey f k x t
979 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
980 -- the keys are in ascending order.
981 fromAscList :: [(Key,a)] -> IntMap a
985 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
986 -- the keys are in ascending order, with a combining function on equal keys.
987 fromAscListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a
991 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
992 -- the keys are in ascending order, with a combining function on equal keys.
993 fromAscListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a
994 fromAscListWithKey f xs
995 = fromListWithKey f xs
997 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
998 -- the keys are in ascending order and all distinct.
999 fromDistinctAscList :: [(Key,a)] -> IntMap a
1000 fromDistinctAscList xs
1004 {--------------------------------------------------------------------
1006 --------------------------------------------------------------------}
1007 instance Eq a => Eq (IntMap a) where
1008 t1 == t2 = equal t1 t2
1009 t1 /= t2 = nequal t1 t2
1011 equal :: Eq a => IntMap a -> IntMap a -> Bool
1012 equal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
1013 = (m1 == m2) && (p1 == p2) && (equal l1 l2) && (equal r1 r2)
1014 equal (Tip kx x) (Tip ky y)
1015 = (kx == ky) && (x==y)
1016 equal Nil Nil = True
1019 nequal :: Eq a => IntMap a -> IntMap a -> Bool
1020 nequal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
1021 = (m1 /= m2) || (p1 /= p2) || (nequal l1 l2) || (nequal r1 r2)
1022 nequal (Tip kx x) (Tip ky y)
1023 = (kx /= ky) || (x/=y)
1024 nequal Nil Nil = False
1027 {--------------------------------------------------------------------
1029 --------------------------------------------------------------------}
1031 instance Ord a => Ord (IntMap a) where
1032 compare m1 m2 = compare (toList m1) (toList m2)
1034 {--------------------------------------------------------------------
1036 --------------------------------------------------------------------}
1038 instance Functor IntMap where
1041 {--------------------------------------------------------------------
1043 --------------------------------------------------------------------}
1045 instance Show a => Show (IntMap a) where
1046 showsPrec d m = showParen (d > 10) $
1047 showString "fromList " . shows (toList m)
1049 showMap :: (Show a) => [(Key,a)] -> ShowS
1053 = showChar '{' . showElem x . showTail xs
1055 showTail [] = showChar '}'
1056 showTail (x:xs) = showChar ',' . showElem x . showTail xs
1058 showElem (k,x) = shows k . showString ":=" . shows x
1060 {--------------------------------------------------------------------
1062 --------------------------------------------------------------------}
1063 instance (Read e) => Read (IntMap e) where
1064 #ifdef __GLASGOW_HASKELL__
1065 readPrec = parens $ prec 10 $ do
1066 Ident "fromList" <- lexP
1068 return (fromList xs)
1070 readListPrec = readListPrecDefault
1072 readsPrec p = readParen (p > 10) $ \ r -> do
1073 ("fromList",s) <- lex r
1075 return (fromList xs,t)
1078 {--------------------------------------------------------------------
1080 --------------------------------------------------------------------}
1082 #include "Typeable.h"
1083 INSTANCE_TYPEABLE1(IntMap,intMapTc,"IntMap")
1085 {--------------------------------------------------------------------
1087 --------------------------------------------------------------------}
1088 -- | /O(n)/. Show the tree that implements the map. The tree is shown
1089 -- in a compressed, hanging format.
1090 showTree :: Show a => IntMap a -> String
1092 = showTreeWith True False s
1095 {- | /O(n)/. The expression (@'showTreeWith' hang wide map@) shows
1096 the tree that implements the map. If @hang@ is
1097 'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
1098 @wide@ is 'True', an extra wide version is shown.
1100 showTreeWith :: Show a => Bool -> Bool -> IntMap a -> String
1101 showTreeWith hang wide t
1102 | hang = (showsTreeHang wide [] t) ""
1103 | otherwise = (showsTree wide [] [] t) ""
1105 showsTree :: Show a => Bool -> [String] -> [String] -> IntMap a -> ShowS
1106 showsTree wide lbars rbars t
1109 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
1110 showWide wide rbars .
1111 showsBars lbars . showString (showBin p m) . showString "\n" .
1112 showWide wide lbars .
1113 showsTree wide (withEmpty lbars) (withBar lbars) l
1115 -> showsBars lbars . showString " " . shows k . showString ":=" . shows x . showString "\n"
1116 Nil -> showsBars lbars . showString "|\n"
1118 showsTreeHang :: Show a => Bool -> [String] -> IntMap a -> ShowS
1119 showsTreeHang wide bars t
1122 -> showsBars bars . showString (showBin p m) . showString "\n" .
1123 showWide wide bars .
1124 showsTreeHang wide (withBar bars) l .
1125 showWide wide bars .
1126 showsTreeHang wide (withEmpty bars) r
1128 -> showsBars bars . showString " " . shows k . showString ":=" . shows x . showString "\n"
1129 Nil -> showsBars bars . showString "|\n"
1132 = "*" -- ++ show (p,m)
1135 | wide = showString (concat (reverse bars)) . showString "|\n"
1138 showsBars :: [String] -> ShowS
1142 _ -> showString (concat (reverse (tail bars))) . showString node
1145 withBar bars = "| ":bars
1146 withEmpty bars = " ":bars
1149 {--------------------------------------------------------------------
1151 --------------------------------------------------------------------}
1152 {--------------------------------------------------------------------
1154 --------------------------------------------------------------------}
1155 join :: Prefix -> IntMap a -> Prefix -> IntMap a -> IntMap a
1157 | zero p1 m = Bin p m t1 t2
1158 | otherwise = Bin p m t2 t1
1160 m = branchMask p1 p2
1163 {--------------------------------------------------------------------
1164 @bin@ assures that we never have empty trees within a tree.
1165 --------------------------------------------------------------------}
1166 bin :: Prefix -> Mask -> IntMap a -> IntMap a -> IntMap a
1169 bin p m l r = Bin p m l r
1172 {--------------------------------------------------------------------
1173 Endian independent bit twiddling
1174 --------------------------------------------------------------------}
1175 zero :: Key -> Mask -> Bool
1177 = (natFromInt i) .&. (natFromInt m) == 0
1179 nomatch,match :: Key -> Prefix -> Mask -> Bool
1186 mask :: Key -> Mask -> Prefix
1188 = maskW (natFromInt i) (natFromInt m)
1191 zeroN :: Nat -> Nat -> Bool
1192 zeroN i m = (i .&. m) == 0
1194 {--------------------------------------------------------------------
1195 Big endian operations
1196 --------------------------------------------------------------------}
1197 maskW :: Nat -> Nat -> Prefix
1199 = intFromNat (i .&. (complement (m-1) `xor` m))
1201 shorter :: Mask -> Mask -> Bool
1203 = (natFromInt m1) > (natFromInt m2)
1205 branchMask :: Prefix -> Prefix -> Mask
1207 = intFromNat (highestBitMask (natFromInt p1 `xor` natFromInt p2))
1209 {----------------------------------------------------------------------
1210 Finding the highest bit (mask) in a word [x] can be done efficiently in
1212 * convert to a floating point value and the mantissa tells us the
1213 [log2(x)] that corresponds with the highest bit position. The mantissa
1214 is retrieved either via the standard C function [frexp] or by some bit
1215 twiddling on IEEE compatible numbers (float). Note that one needs to
1216 use at least [double] precision for an accurate mantissa of 32 bit
1218 * use bit twiddling, a logarithmic sequence of bitwise or's and shifts (bit).
1219 * use processor specific assembler instruction (asm).
1221 The most portable way would be [bit], but is it efficient enough?
1222 I have measured the cycle counts of the different methods on an AMD
1223 Athlon-XP 1800 (~ Pentium III 1.8Ghz) using the RDTSC instruction:
1225 highestBitMask: method cycles
1232 highestBit: method cycles
1239 Wow, the bit twiddling is on today's RISC like machines even faster
1240 than a single CISC instruction (BSR)!
1241 ----------------------------------------------------------------------}
1243 {----------------------------------------------------------------------
1244 [highestBitMask] returns a word where only the highest bit is set.
1245 It is found by first setting all bits in lower positions than the
1246 highest bit and than taking an exclusive or with the original value.
1247 Allthough the function may look expensive, GHC compiles this into
1248 excellent C code that subsequently compiled into highly efficient
1249 machine code. The algorithm is derived from Jorg Arndt's FXT library.
1250 ----------------------------------------------------------------------}
1251 highestBitMask :: Nat -> Nat
1253 = case (x .|. shiftRL x 1) of
1254 x -> case (x .|. shiftRL x 2) of
1255 x -> case (x .|. shiftRL x 4) of
1256 x -> case (x .|. shiftRL x 8) of
1257 x -> case (x .|. shiftRL x 16) of
1258 x -> case (x .|. shiftRL x 32) of -- for 64 bit platforms
1259 x -> (x `xor` (shiftRL x 1))
1262 {--------------------------------------------------------------------
1264 --------------------------------------------------------------------}
1268 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
1271 {--------------------------------------------------------------------
1273 --------------------------------------------------------------------}
1274 testTree :: [Int] -> IntMap Int
1275 testTree xs = fromList [(x,x*x*30696 `mod` 65521) | x <- xs]
1276 test1 = testTree [1..20]
1277 test2 = testTree [30,29..10]
1278 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1280 {--------------------------------------------------------------------
1282 --------------------------------------------------------------------}
1287 { configMaxTest = 500
1288 , configMaxFail = 5000
1289 , configSize = \n -> (div n 2 + 3)
1290 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1294 {--------------------------------------------------------------------
1295 Arbitrary, reasonably balanced trees
1296 --------------------------------------------------------------------}
1297 instance Arbitrary a => Arbitrary (IntMap a) where
1298 arbitrary = do{ ks <- arbitrary
1299 ; xs <- mapM (\k -> do{ x <- arbitrary; return (k,x)}) ks
1300 ; return (fromList xs)
1304 {--------------------------------------------------------------------
1305 Single, Insert, Delete
1306 --------------------------------------------------------------------}
1307 prop_Single :: Key -> Int -> Bool
1309 = (insert k x empty == singleton k x)
1311 prop_InsertDelete :: Key -> Int -> IntMap Int -> Property
1312 prop_InsertDelete k x t
1313 = not (member k t) ==> delete k (insert k x t) == t
1315 prop_UpdateDelete :: Key -> IntMap Int -> Bool
1316 prop_UpdateDelete k t
1317 = update (const Nothing) k t == delete k t
1320 {--------------------------------------------------------------------
1322 --------------------------------------------------------------------}
1323 prop_UnionInsert :: Key -> Int -> IntMap Int -> Bool
1324 prop_UnionInsert k x t
1325 = union (singleton k x) t == insert k x t
1327 prop_UnionAssoc :: IntMap Int -> IntMap Int -> IntMap Int -> Bool
1328 prop_UnionAssoc t1 t2 t3
1329 = union t1 (union t2 t3) == union (union t1 t2) t3
1331 prop_UnionComm :: IntMap Int -> IntMap Int -> Bool
1332 prop_UnionComm t1 t2
1333 = (union t1 t2 == unionWith (\x y -> y) t2 t1)
1336 prop_Diff :: [(Key,Int)] -> [(Key,Int)] -> Bool
1338 = List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys)))
1339 == List.sort ((List.\\) (nub (Prelude.map fst xs)) (nub (Prelude.map fst ys)))
1341 prop_Int :: [(Key,Int)] -> [(Key,Int)] -> Bool
1343 = List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys)))
1344 == List.sort (nub ((List.intersect) (Prelude.map fst xs) (Prelude.map fst ys)))
1346 {--------------------------------------------------------------------
1348 --------------------------------------------------------------------}
1350 = forAll (choose (5,100)) $ \n ->
1351 let xs = [(x,()) | x <- [0..n::Int]]
1352 in fromAscList xs == fromList xs
1354 prop_List :: [Key] -> Bool
1356 = (sort (nub xs) == [x | (x,()) <- toAscList (fromList [(x,()) | x <- xs])])