1 {-# OPTIONS -cpp -fglasgow-exts #-}
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
57 , insertWith, insertWithKey, insertLookupWithKey
114 , fromDistinctAscList
126 , isSubmapOf, isSubmapOfBy
127 , isProperSubmapOf, isProperSubmapOfBy
135 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
139 import qualified Data.IntSet as IntSet
144 import qualified Prelude
145 import Debug.QuickCheck
146 import List (nub,sort)
147 import qualified List
150 #if __GLASGOW_HASKELL__ >= 503
152 import GHC.Exts ( Word(..), Int(..), shiftRL# )
153 #elif __GLASGOW_HASKELL__
155 import GlaExts ( Word(..), Int(..), shiftRL# )
160 infixl 9 \\{-This comment teaches CPP correct behaviour -}
162 -- A "Nat" is a natural machine word (an unsigned Int)
165 natFromInt :: Key -> Nat
166 natFromInt i = fromIntegral i
168 intFromNat :: Nat -> Key
169 intFromNat w = fromIntegral w
171 shiftRL :: Nat -> Key -> Nat
172 #if __GLASGOW_HASKELL__
173 {--------------------------------------------------------------------
174 GHC: use unboxing to get @shiftRL@ inlined.
175 --------------------------------------------------------------------}
176 shiftRL (W# x) (I# i)
179 shiftRL x i = shiftR x i
182 {--------------------------------------------------------------------
184 --------------------------------------------------------------------}
186 -- | /O(min(n,W))/. Find the value of a key. Calls @error@ when the element can not be found.
188 (!) :: IntMap a -> Key -> a
191 -- | /O(n+m)/. See 'difference'.
192 (\\) :: IntMap a -> IntMap b -> IntMap a
193 m1 \\ m2 = difference m1 m2
195 {--------------------------------------------------------------------
197 --------------------------------------------------------------------}
198 -- | A map of integers to values @a@.
200 | Tip {-# UNPACK #-} !Key a
201 | Bin {-# UNPACK #-} !Prefix {-# UNPACK #-} !Mask !(IntMap a) !(IntMap a)
207 {--------------------------------------------------------------------
209 --------------------------------------------------------------------}
210 -- | /O(1)/. Is the map empty?
211 null :: IntMap a -> Bool
215 -- | /O(n)/. Number of elements in the map.
216 size :: IntMap a -> Int
219 Bin p m l r -> size l + size r
223 -- | /O(min(n,W))/. Is the key a member of the map?
224 member :: Key -> IntMap a -> Bool
230 -- | /O(min(n,W))/. Lookup the value of a key in the map.
231 lookup :: Key -> IntMap a -> Maybe a
233 = let nk = natFromInt k in seq nk (lookupN nk t)
235 lookupN :: Nat -> IntMap a -> Maybe a
239 | zeroN k (natFromInt m) -> lookupN k l
240 | otherwise -> lookupN k r
242 | (k == natFromInt kx) -> Just x
243 | otherwise -> Nothing
246 find' :: Key -> IntMap a -> a
249 Nothing -> error ("IntMap.find: key " ++ show k ++ " is not an element of the map")
253 -- | /O(min(n,W))/. The expression @(findWithDefault def k map)@ returns the value of key @k@ or returns @def@ when
254 -- the key is not an element of the map.
255 findWithDefault :: a -> Key -> IntMap a -> a
256 findWithDefault def k m
261 {--------------------------------------------------------------------
263 --------------------------------------------------------------------}
264 -- | /O(1)/. The empty map.
269 -- | /O(1)/. A map of one element.
270 singleton :: Key -> a -> IntMap a
274 {--------------------------------------------------------------------
276 'insert' is the inlined version of 'insertWith (\k x y -> x)'
277 --------------------------------------------------------------------}
278 -- | /O(min(n,W))/. Insert a new key\/value pair in the map. When the key
279 -- is already an element of the set, its value is replaced by the new value,
280 -- ie. 'insert' is left-biased.
281 insert :: Key -> a -> IntMap a -> IntMap a
285 | nomatch k p m -> join k (Tip k x) p t
286 | zero k m -> Bin p m (insert k x l) r
287 | otherwise -> Bin p m l (insert k x r)
290 | otherwise -> join k (Tip k x) ky t
293 -- right-biased insertion, used by 'union'
294 -- | /O(min(n,W))/. Insert with a combining function.
295 insertWith :: (a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
297 = insertWithKey (\k x y -> f x y) k x t
299 -- | /O(min(n,W))/. Insert with a combining function.
300 insertWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> IntMap a
301 insertWithKey f k x t
304 | nomatch k p m -> join k (Tip k x) p t
305 | zero k m -> Bin p m (insertWithKey f k x l) r
306 | otherwise -> Bin p m l (insertWithKey f k x r)
308 | k==ky -> Tip k (f k x y)
309 | otherwise -> join k (Tip k x) ky t
313 -- | /O(min(n,W))/. The expression (@insertLookupWithKey f k x map@) is a pair where
314 -- the first element is equal to (@lookup k map@) and the second element
315 -- equal to (@insertWithKey f k x map@).
316 insertLookupWithKey :: (Key -> a -> a -> a) -> Key -> a -> IntMap a -> (Maybe a, IntMap a)
317 insertLookupWithKey f k x t
320 | nomatch k p m -> (Nothing,join k (Tip k x) p t)
321 | zero k m -> let (found,l') = insertLookupWithKey f k x l in (found,Bin p m l' r)
322 | otherwise -> let (found,r') = insertLookupWithKey f k x r in (found,Bin p m l r')
324 | k==ky -> (Just y,Tip k (f k x y))
325 | otherwise -> (Nothing,join k (Tip k x) ky t)
326 Nil -> (Nothing,Tip k x)
329 {--------------------------------------------------------------------
331 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
332 --------------------------------------------------------------------}
333 -- | /O(min(n,W))/. Delete a key and its value from the map. When the key is not
334 -- a member of the map, the original map is returned.
335 delete :: Key -> IntMap a -> IntMap a
340 | zero k m -> bin p m (delete k l) r
341 | otherwise -> bin p m l (delete k r)
347 -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
348 -- a member of the map, the original map is returned.
349 adjust :: (a -> a) -> Key -> IntMap a -> IntMap a
351 = adjustWithKey (\k x -> f x) k m
353 -- | /O(min(n,W))/. Adjust a value at a specific key. When the key is not
354 -- a member of the map, the original map is returned.
355 adjustWithKey :: (Key -> a -> a) -> Key -> IntMap a -> IntMap a
357 = updateWithKey (\k x -> Just (f k x)) k m
359 -- | /O(min(n,W))/. The expression (@update f k map@) updates the value @x@
360 -- at @k@ (if it is in the map). If (@f x@) is @Nothing@, the element is
361 -- deleted. If it is (@Just y@), the key @k@ is bound to the new value @y@.
362 update :: (a -> Maybe a) -> Key -> IntMap a -> IntMap a
364 = updateWithKey (\k x -> f x) k m
366 -- | /O(min(n,W))/. The expression (@update f k map@) updates the value @x@
367 -- at @k@ (if it is in the map). If (@f k x@) is @Nothing@, the element is
368 -- deleted. If it is (@Just y@), the key @k@ is bound to the new value @y@.
369 updateWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> IntMap a
374 | zero k m -> bin p m (updateWithKey f k l) r
375 | otherwise -> bin p m l (updateWithKey f k r)
377 | k==ky -> case (f k y) of
383 -- | /O(min(n,W))/. Lookup and update.
384 updateLookupWithKey :: (Key -> a -> Maybe a) -> Key -> IntMap a -> (Maybe a,IntMap a)
385 updateLookupWithKey f k t
388 | nomatch k p m -> (Nothing,t)
389 | zero k m -> let (found,l') = updateLookupWithKey f k l in (found,bin p m l' r)
390 | otherwise -> let (found,r') = updateLookupWithKey f k r in (found,bin p m l r')
392 | k==ky -> case (f k y) of
393 Just y' -> (Just y,Tip ky y')
394 Nothing -> (Just y,Nil)
395 | otherwise -> (Nothing,t)
399 {--------------------------------------------------------------------
401 --------------------------------------------------------------------}
402 -- | The union of a list of maps.
403 unions :: [IntMap a] -> IntMap a
405 = foldlStrict union empty xs
407 -- | The union of a list of maps, with a combining operation
408 unionsWith :: (a->a->a) -> [IntMap a] -> IntMap a
410 = foldlStrict (unionWith f) empty ts
412 -- | /O(n+m)/. The (left-biased) union of two sets.
413 union :: IntMap a -> IntMap a -> IntMap a
414 union t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
415 | shorter m1 m2 = union1
416 | shorter m2 m1 = union2
417 | p1 == p2 = Bin p1 m1 (union l1 l2) (union r1 r2)
418 | otherwise = join p1 t1 p2 t2
420 union1 | nomatch p2 p1 m1 = join p1 t1 p2 t2
421 | zero p2 m1 = Bin p1 m1 (union l1 t2) r1
422 | otherwise = Bin p1 m1 l1 (union r1 t2)
424 union2 | nomatch p1 p2 m2 = join p1 t1 p2 t2
425 | zero p1 m2 = Bin p2 m2 (union t1 l2) r2
426 | otherwise = Bin p2 m2 l2 (union t1 r2)
428 union (Tip k x) t = insert k x t
429 union t (Tip k x) = insertWith (\x y -> y) k x t -- right bias
433 -- | /O(n+m)/. The union with a combining function.
434 unionWith :: (a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
436 = unionWithKey (\k x y -> f x y) m1 m2
438 -- | /O(n+m)/. The union with a combining function.
439 unionWithKey :: (Key -> a -> a -> a) -> IntMap a -> IntMap a -> IntMap a
440 unionWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
441 | shorter m1 m2 = union1
442 | shorter m2 m1 = union2
443 | p1 == p2 = Bin p1 m1 (unionWithKey f l1 l2) (unionWithKey f r1 r2)
444 | otherwise = join p1 t1 p2 t2
446 union1 | nomatch p2 p1 m1 = join p1 t1 p2 t2
447 | zero p2 m1 = Bin p1 m1 (unionWithKey f l1 t2) r1
448 | otherwise = Bin p1 m1 l1 (unionWithKey f r1 t2)
450 union2 | nomatch p1 p2 m2 = join p1 t1 p2 t2
451 | zero p1 m2 = Bin p2 m2 (unionWithKey f t1 l2) r2
452 | otherwise = Bin p2 m2 l2 (unionWithKey f t1 r2)
454 unionWithKey f (Tip k x) t = insertWithKey f k x t
455 unionWithKey f t (Tip k x) = insertWithKey (\k x y -> f k y x) k x t -- right bias
456 unionWithKey f Nil t = t
457 unionWithKey f t Nil = t
459 {--------------------------------------------------------------------
461 --------------------------------------------------------------------}
462 -- | /O(n+m)/. Difference between two maps (based on keys).
463 difference :: IntMap a -> IntMap b -> IntMap a
464 difference t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
465 | shorter m1 m2 = difference1
466 | shorter m2 m1 = difference2
467 | p1 == p2 = bin p1 m1 (difference l1 l2) (difference r1 r2)
470 difference1 | nomatch p2 p1 m1 = t1
471 | zero p2 m1 = bin p1 m1 (difference l1 t2) r1
472 | otherwise = bin p1 m1 l1 (difference r1 t2)
474 difference2 | nomatch p1 p2 m2 = t1
475 | zero p1 m2 = difference t1 l2
476 | otherwise = difference t1 r2
478 difference t1@(Tip k x) t2
482 difference Nil t = Nil
483 difference t (Tip k x) = delete k t
486 -- | /O(n+m)/. Difference with a combining function.
487 differenceWith :: (a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
488 differenceWith f m1 m2
489 = differenceWithKey (\k x y -> f x y) m1 m2
491 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
492 -- encountered, the combining function is applied to the key and both values.
493 -- If it returns @Nothing@, the element is discarded (proper set difference). If
494 -- it returns (@Just y@), the element is updated with a new value @y@.
495 differenceWithKey :: (Key -> a -> b -> Maybe a) -> IntMap a -> IntMap b -> IntMap a
496 differenceWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
497 | shorter m1 m2 = difference1
498 | shorter m2 m1 = difference2
499 | p1 == p2 = bin p1 m1 (differenceWithKey f l1 l2) (differenceWithKey f r1 r2)
502 difference1 | nomatch p2 p1 m1 = t1
503 | zero p2 m1 = bin p1 m1 (differenceWithKey f l1 t2) r1
504 | otherwise = bin p1 m1 l1 (differenceWithKey f r1 t2)
506 difference2 | nomatch p1 p2 m2 = t1
507 | zero p1 m2 = differenceWithKey f t1 l2
508 | otherwise = differenceWithKey f t1 r2
510 differenceWithKey f t1@(Tip k x) t2
511 = case lookup k t2 of
512 Just y -> case f k x y of
517 differenceWithKey f Nil t = Nil
518 differenceWithKey f t (Tip k y) = updateWithKey (\k x -> f k x y) k t
519 differenceWithKey f t Nil = t
522 {--------------------------------------------------------------------
524 --------------------------------------------------------------------}
525 -- | /O(n+m)/. The (left-biased) intersection of two maps (based on keys).
526 intersection :: IntMap a -> IntMap b -> IntMap a
527 intersection t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
528 | shorter m1 m2 = intersection1
529 | shorter m2 m1 = intersection2
530 | p1 == p2 = bin p1 m1 (intersection l1 l2) (intersection r1 r2)
533 intersection1 | nomatch p2 p1 m1 = Nil
534 | zero p2 m1 = intersection l1 t2
535 | otherwise = intersection r1 t2
537 intersection2 | nomatch p1 p2 m2 = Nil
538 | zero p1 m2 = intersection t1 l2
539 | otherwise = intersection t1 r2
541 intersection t1@(Tip k x) t2
544 intersection t (Tip k x)
548 intersection Nil t = Nil
549 intersection t Nil = Nil
551 -- | /O(n+m)/. The intersection with a combining function.
552 intersectionWith :: (a -> b -> a) -> IntMap a -> IntMap b -> IntMap a
553 intersectionWith f m1 m2
554 = intersectionWithKey (\k x y -> f x y) m1 m2
556 -- | /O(n+m)/. The intersection with a combining function.
557 intersectionWithKey :: (Key -> a -> b -> a) -> IntMap a -> IntMap b -> IntMap a
558 intersectionWithKey f t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
559 | shorter m1 m2 = intersection1
560 | shorter m2 m1 = intersection2
561 | p1 == p2 = bin p1 m1 (intersectionWithKey f l1 l2) (intersectionWithKey f r1 r2)
564 intersection1 | nomatch p2 p1 m1 = Nil
565 | zero p2 m1 = intersectionWithKey f l1 t2
566 | otherwise = intersectionWithKey f r1 t2
568 intersection2 | nomatch p1 p2 m2 = Nil
569 | zero p1 m2 = intersectionWithKey f t1 l2
570 | otherwise = intersectionWithKey f t1 r2
572 intersectionWithKey f t1@(Tip k x) t2
573 = case lookup k t2 of
574 Just y -> Tip k (f k x y)
576 intersectionWithKey f t1 (Tip k y)
577 = case lookup k t1 of
578 Just x -> Tip k (f k x y)
580 intersectionWithKey f Nil t = Nil
581 intersectionWithKey f t Nil = Nil
584 {--------------------------------------------------------------------
586 --------------------------------------------------------------------}
587 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
588 -- Defined as (@isProperSubmapOf = isProperSubmapOfBy (==)@).
589 isProperSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
590 isProperSubmapOf m1 m2
591 = isProperSubmapOfBy (==) m1 m2
593 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
594 The expression (@isProperSubmapOfBy f m1 m2@) returns @True@ when
595 @m1@ and @m2@ are not equal,
596 all keys in @m1@ are in @m2@, and when @f@ returns @True@ when
597 applied to their respective values. For example, the following
598 expressions are all @True@.
600 > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
601 > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
603 But the following are all @False@:
605 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
606 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
607 > isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
609 isProperSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
610 isProperSubmapOfBy pred t1 t2
611 = case submapCmp pred t1 t2 of
615 submapCmp pred t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
617 | shorter m2 m1 = submapCmpLt
618 | p1 == p2 = submapCmpEq
619 | otherwise = GT -- disjoint
621 submapCmpLt | nomatch p1 p2 m2 = GT
622 | zero p1 m2 = submapCmp pred t1 l2
623 | otherwise = submapCmp pred t1 r2
624 submapCmpEq = case (submapCmp pred l1 l2, submapCmp pred r1 r2) of
630 submapCmp pred (Bin p m l r) t = GT
631 submapCmp pred (Tip kx x) (Tip ky y)
632 | (kx == ky) && pred x y = EQ
633 | otherwise = GT -- disjoint
634 submapCmp pred (Tip k x) t
636 Just y | pred x y -> LT
637 other -> GT -- disjoint
638 submapCmp pred Nil Nil = EQ
639 submapCmp pred Nil t = LT
641 -- | /O(n+m)/. Is this a submap? Defined as (@isSubmapOf = isSubmapOfBy (==)@).
642 isSubmapOf :: Eq a => IntMap a -> IntMap a -> Bool
644 = isSubmapOfBy (==) m1 m2
647 The expression (@isSubmapOfBy f m1 m2@) returns @True@ if
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 > isSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
653 > isSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
654 > isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
656 But the following are all @False@:
658 > isSubmapOfBy (==) (fromList [(1,2)]) (fromList [(1,1),(2,2)])
659 > isSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
660 > isSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
663 isSubmapOfBy :: (a -> b -> Bool) -> IntMap a -> IntMap b -> Bool
664 isSubmapOfBy pred t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
665 | shorter m1 m2 = False
666 | shorter m2 m1 = match p1 p2 m2 && (if zero p1 m2 then isSubmapOfBy pred t1 l2
667 else isSubmapOfBy pred t1 r2)
668 | otherwise = (p1==p2) && isSubmapOfBy pred l1 l2 && isSubmapOfBy pred r1 r2
669 isSubmapOfBy pred (Bin p m l r) t = False
670 isSubmapOfBy pred (Tip k x) t = case lookup k t of
673 isSubmapOfBy pred Nil t = True
675 {--------------------------------------------------------------------
677 --------------------------------------------------------------------}
678 -- | /O(n)/. Map a function over all values in the map.
679 map :: (a -> b) -> IntMap a -> IntMap b
681 = mapWithKey (\k x -> f x) m
683 -- | /O(n)/. Map a function over all values in the map.
684 mapWithKey :: (Key -> a -> b) -> IntMap a -> IntMap b
687 Bin p m l r -> Bin p m (mapWithKey f l) (mapWithKey f r)
688 Tip k x -> Tip k (f k x)
691 -- | /O(n)/. The function @mapAccum@ threads an accumulating
692 -- argument through the map in an unspecified order.
693 mapAccum :: (a -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
695 = mapAccumWithKey (\a k x -> f a x) a m
697 -- | /O(n)/. The function @mapAccumWithKey@ threads an accumulating
698 -- argument through the map in an unspecified order.
699 mapAccumWithKey :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
700 mapAccumWithKey f a t
703 -- | /O(n)/. The function @mapAccumL@ threads an accumulating
704 -- argument through the map in pre-order.
705 mapAccumL :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
708 Bin p m l r -> let (a1,l') = mapAccumL f a l
709 (a2,r') = mapAccumL f a1 r
710 in (a2,Bin p m l' r')
711 Tip k x -> let (a',x') = f a k x in (a',Tip k x')
715 -- | /O(n)/. The function @mapAccumR@ threads an accumulating
716 -- argument throught the map in post-order.
717 mapAccumR :: (a -> Key -> b -> (a,c)) -> a -> IntMap b -> (a,IntMap c)
720 Bin p m l r -> let (a1,r') = mapAccumR f a r
721 (a2,l') = mapAccumR f a1 l
722 in (a2,Bin p m l' r')
723 Tip k x -> let (a',x') = f a k x in (a',Tip k x')
726 {--------------------------------------------------------------------
728 --------------------------------------------------------------------}
729 -- | /O(n)/. Filter all values that satisfy some predicate.
730 filter :: (a -> Bool) -> IntMap a -> IntMap a
732 = filterWithKey (\k x -> p x) m
734 -- | /O(n)/. Filter all keys\/values that satisfy some predicate.
735 filterWithKey :: (Key -> a -> Bool) -> IntMap a -> IntMap a
739 -> bin p m (filterWithKey pred l) (filterWithKey pred r)
745 -- | /O(n)/. partition the map according to some predicate. The first
746 -- map contains all elements that satisfy the predicate, the second all
747 -- elements that fail the predicate. See also 'split'.
748 partition :: (a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
750 = partitionWithKey (\k x -> p x) m
752 -- | /O(n)/. partition the map according to some predicate. The first
753 -- map contains all elements that satisfy the predicate, the second all
754 -- elements that fail the predicate. See also 'split'.
755 partitionWithKey :: (Key -> a -> Bool) -> IntMap a -> (IntMap a,IntMap a)
756 partitionWithKey pred t
759 -> let (l1,l2) = partitionWithKey pred l
760 (r1,r2) = partitionWithKey pred r
761 in (bin p m l1 r1, bin p m l2 r2)
763 | pred k x -> (t,Nil)
764 | otherwise -> (Nil,t)
768 -- | /O(log n)/. The expression (@split k map@) is a pair @(map1,map2)@
769 -- where all keys in @map1@ are lower than @k@ and all keys in
770 -- @map2@ larger than @k@. Any key equal to @k@ is found in neither @map1@ nor @map2@.
771 split :: Key -> IntMap a -> (IntMap a,IntMap a)
775 | zero k m -> let (lt,gt) = split k l in (lt,union gt r)
776 | otherwise -> let (lt,gt) = split k r in (union l lt,gt)
780 | otherwise -> (Nil,Nil)
783 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
784 -- key was found in the original map.
785 splitLookup :: Key -> IntMap a -> (Maybe a,IntMap a,IntMap a)
789 | zero k m -> let (found,lt,gt) = splitLookup k l in (found,lt,union gt r)
790 | otherwise -> let (found,lt,gt) = splitLookup k r in (found,union l lt,gt)
792 | k>ky -> (Nothing,t,Nil)
793 | k<ky -> (Nothing,Nil,t)
794 | otherwise -> (Just y,Nil,Nil)
795 Nil -> (Nothing,Nil,Nil)
797 {--------------------------------------------------------------------
799 --------------------------------------------------------------------}
800 -- | /O(n)/. Fold over the elements of a map in an unspecified order.
802 -- > sum map = fold (+) 0 map
803 -- > elems map = fold (:) [] map
804 fold :: (a -> b -> b) -> b -> IntMap a -> b
806 = foldWithKey (\k x y -> f x y) z t
808 -- | /O(n)/. Fold over the elements of a map in an unspecified order.
810 -- > keys map = foldWithKey (\k x ks -> k:ks) [] map
811 foldWithKey :: (Key -> a -> b -> b) -> b -> IntMap a -> b
815 foldr :: (Key -> a -> b -> b) -> b -> IntMap a -> b
818 Bin p m l r -> foldr f (foldr f z r) l
822 {--------------------------------------------------------------------
824 --------------------------------------------------------------------}
825 -- | /O(n)/. Return all elements of the map.
826 elems :: IntMap a -> [a]
828 = foldWithKey (\k x xs -> x:xs) [] m
830 -- | /O(n)/. Return all keys of the map.
831 keys :: IntMap a -> [Key]
833 = foldWithKey (\k x ks -> k:ks) [] m
835 -- | /O(n*min(n,W))/. The set of all keys of the map.
836 keysSet :: IntMap a -> IntSet.IntSet
837 keysSet m = IntSet.fromDistinctAscList (keys m)
840 -- | /O(n)/. Return all key\/value pairs in the map.
841 assocs :: IntMap a -> [(Key,a)]
846 {--------------------------------------------------------------------
848 --------------------------------------------------------------------}
849 -- | /O(n)/. Convert the map to a list of key\/value pairs.
850 toList :: IntMap a -> [(Key,a)]
852 = foldWithKey (\k x xs -> (k,x):xs) [] t
854 -- | /O(n)/. Convert the map to a list of key\/value pairs where the
855 -- keys are in ascending order.
856 toAscList :: IntMap a -> [(Key,a)]
858 = -- NOTE: the following algorithm only works for big-endian trees
859 let (pos,neg) = span (\(k,x) -> k >=0) (foldr (\k x xs -> (k,x):xs) [] t) in neg ++ pos
861 -- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs.
862 fromList :: [(Key,a)] -> IntMap a
864 = foldlStrict ins empty xs
866 ins t (k,x) = insert k x t
868 -- | /O(n*min(n,W))/. Create a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
869 fromListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a
871 = fromListWithKey (\k x y -> f x y) xs
873 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs with a combining function. See also fromAscListWithKey'.
874 fromListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a
876 = foldlStrict ins empty xs
878 ins t (k,x) = insertWithKey f k x t
880 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
881 -- the keys are in ascending order.
882 fromAscList :: [(Key,a)] -> IntMap a
886 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
887 -- the keys are in ascending order, with a combining function on equal keys.
888 fromAscListWith :: (a -> a -> a) -> [(Key,a)] -> IntMap a
892 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
893 -- the keys are in ascending order, with a combining function on equal keys.
894 fromAscListWithKey :: (Key -> a -> a -> a) -> [(Key,a)] -> IntMap a
895 fromAscListWithKey f xs
896 = fromListWithKey f xs
898 -- | /O(n*min(n,W))/. Build a map from a list of key\/value pairs where
899 -- the keys are in ascending order and all distinct.
900 fromDistinctAscList :: [(Key,a)] -> IntMap a
901 fromDistinctAscList xs
905 {--------------------------------------------------------------------
907 --------------------------------------------------------------------}
908 instance Eq a => Eq (IntMap a) where
909 t1 == t2 = equal t1 t2
910 t1 /= t2 = nequal t1 t2
912 equal :: Eq a => IntMap a -> IntMap a -> Bool
913 equal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
914 = (m1 == m2) && (p1 == p2) && (equal l1 l2) && (equal r1 r2)
915 equal (Tip kx x) (Tip ky y)
916 = (kx == ky) && (x==y)
920 nequal :: Eq a => IntMap a -> IntMap a -> Bool
921 nequal (Bin p1 m1 l1 r1) (Bin p2 m2 l2 r2)
922 = (m1 /= m2) || (p1 /= p2) || (nequal l1 l2) || (nequal r1 r2)
923 nequal (Tip kx x) (Tip ky y)
924 = (kx /= ky) || (x/=y)
925 nequal Nil Nil = False
928 {--------------------------------------------------------------------
930 --------------------------------------------------------------------}
932 instance Ord a => Ord (IntMap a) where
933 compare m1 m2 = compare (toList m1) (toList m2)
935 {--------------------------------------------------------------------
937 --------------------------------------------------------------------}
939 instance Functor IntMap where
942 {--------------------------------------------------------------------
944 --------------------------------------------------------------------}
946 instance Ord a => Monoid (IntMap a) where
951 {--------------------------------------------------------------------
953 --------------------------------------------------------------------}
955 instance Show a => Show (IntMap a) where
956 showsPrec d t = showMap (toList t)
959 showMap :: (Show a) => [(Key,a)] -> ShowS
963 = showChar '{' . showElem x . showTail xs
965 showTail [] = showChar '}'
966 showTail (x:xs) = showChar ',' . showElem x . showTail xs
968 showElem (k,x) = shows k . showString ":=" . shows x
970 {--------------------------------------------------------------------
972 --------------------------------------------------------------------}
974 #include "Typeable.h"
975 INSTANCE_TYPEABLE1(IntMap,intMapTc,"IntMap")
977 {--------------------------------------------------------------------
979 --------------------------------------------------------------------}
980 -- | /O(n)/. Show the tree that implements the map. The tree is shown
981 -- in a compressed, hanging format.
982 showTree :: Show a => IntMap a -> String
984 = showTreeWith True False s
987 {- | /O(n)/. The expression (@showTreeWith hang wide map@) shows
988 the tree that implements the map. If @hang@ is
989 @True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
990 @wide@ is true, an extra wide version is shown.
992 showTreeWith :: Show a => Bool -> Bool -> IntMap a -> String
993 showTreeWith hang wide t
994 | hang = (showsTreeHang wide [] t) ""
995 | otherwise = (showsTree wide [] [] t) ""
997 showsTree :: Show a => Bool -> [String] -> [String] -> IntMap a -> ShowS
998 showsTree wide lbars rbars t
1001 -> showsTree wide (withBar rbars) (withEmpty rbars) r .
1002 showWide wide rbars .
1003 showsBars lbars . showString (showBin p m) . showString "\n" .
1004 showWide wide lbars .
1005 showsTree wide (withEmpty lbars) (withBar lbars) l
1007 -> showsBars lbars . showString " " . shows k . showString ":=" . shows x . showString "\n"
1008 Nil -> showsBars lbars . showString "|\n"
1010 showsTreeHang :: Show a => Bool -> [String] -> IntMap a -> ShowS
1011 showsTreeHang wide bars t
1014 -> showsBars bars . showString (showBin p m) . showString "\n" .
1015 showWide wide bars .
1016 showsTreeHang wide (withBar bars) l .
1017 showWide wide bars .
1018 showsTreeHang wide (withEmpty bars) r
1020 -> showsBars bars . showString " " . shows k . showString ":=" . shows x . showString "\n"
1021 Nil -> showsBars bars . showString "|\n"
1024 = "*" -- ++ show (p,m)
1027 | wide = showString (concat (reverse bars)) . showString "|\n"
1030 showsBars :: [String] -> ShowS
1034 _ -> showString (concat (reverse (tail bars))) . showString node
1037 withBar bars = "| ":bars
1038 withEmpty bars = " ":bars
1041 {--------------------------------------------------------------------
1043 --------------------------------------------------------------------}
1044 {--------------------------------------------------------------------
1046 --------------------------------------------------------------------}
1047 join :: Prefix -> IntMap a -> Prefix -> IntMap a -> IntMap a
1049 | zero p1 m = Bin p m t1 t2
1050 | otherwise = Bin p m t2 t1
1052 m = branchMask p1 p2
1055 {--------------------------------------------------------------------
1056 @bin@ assures that we never have empty trees within a tree.
1057 --------------------------------------------------------------------}
1058 bin :: Prefix -> Mask -> IntMap a -> IntMap a -> IntMap a
1061 bin p m l r = Bin p m l r
1064 {--------------------------------------------------------------------
1065 Endian independent bit twiddling
1066 --------------------------------------------------------------------}
1067 zero :: Key -> Mask -> Bool
1069 = (natFromInt i) .&. (natFromInt m) == 0
1071 nomatch,match :: Key -> Prefix -> Mask -> Bool
1078 mask :: Key -> Mask -> Prefix
1080 = maskW (natFromInt i) (natFromInt m)
1083 zeroN :: Nat -> Nat -> Bool
1084 zeroN i m = (i .&. m) == 0
1086 {--------------------------------------------------------------------
1087 Big endian operations
1088 --------------------------------------------------------------------}
1089 maskW :: Nat -> Nat -> Prefix
1091 = intFromNat (i .&. (complement (m-1) `xor` m))
1093 shorter :: Mask -> Mask -> Bool
1095 = (natFromInt m1) > (natFromInt m2)
1097 branchMask :: Prefix -> Prefix -> Mask
1099 = intFromNat (highestBitMask (natFromInt p1 `xor` natFromInt p2))
1101 {----------------------------------------------------------------------
1102 Finding the highest bit (mask) in a word [x] can be done efficiently in
1104 * convert to a floating point value and the mantissa tells us the
1105 [log2(x)] that corresponds with the highest bit position. The mantissa
1106 is retrieved either via the standard C function [frexp] or by some bit
1107 twiddling on IEEE compatible numbers (float). Note that one needs to
1108 use at least [double] precision for an accurate mantissa of 32 bit
1110 * use bit twiddling, a logarithmic sequence of bitwise or's and shifts (bit).
1111 * use processor specific assembler instruction (asm).
1113 The most portable way would be [bit], but is it efficient enough?
1114 I have measured the cycle counts of the different methods on an AMD
1115 Athlon-XP 1800 (~ Pentium III 1.8Ghz) using the RDTSC instruction:
1117 highestBitMask: method cycles
1124 highestBit: method cycles
1131 Wow, the bit twiddling is on today's RISC like machines even faster
1132 than a single CISC instruction (BSR)!
1133 ----------------------------------------------------------------------}
1135 {----------------------------------------------------------------------
1136 [highestBitMask] returns a word where only the highest bit is set.
1137 It is found by first setting all bits in lower positions than the
1138 highest bit and than taking an exclusive or with the original value.
1139 Allthough the function may look expensive, GHC compiles this into
1140 excellent C code that subsequently compiled into highly efficient
1141 machine code. The algorithm is derived from Jorg Arndt's FXT library.
1142 ----------------------------------------------------------------------}
1143 highestBitMask :: Nat -> Nat
1145 = case (x .|. shiftRL x 1) of
1146 x -> case (x .|. shiftRL x 2) of
1147 x -> case (x .|. shiftRL x 4) of
1148 x -> case (x .|. shiftRL x 8) of
1149 x -> case (x .|. shiftRL x 16) of
1150 x -> case (x .|. shiftRL x 32) of -- for 64 bit platforms
1151 x -> (x `xor` (shiftRL x 1))
1154 {--------------------------------------------------------------------
1156 --------------------------------------------------------------------}
1160 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
1163 {--------------------------------------------------------------------
1165 --------------------------------------------------------------------}
1166 testTree :: [Int] -> IntMap Int
1167 testTree xs = fromList [(x,x*x*30696 `mod` 65521) | x <- xs]
1168 test1 = testTree [1..20]
1169 test2 = testTree [30,29..10]
1170 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1172 {--------------------------------------------------------------------
1174 --------------------------------------------------------------------}
1179 { configMaxTest = 500
1180 , configMaxFail = 5000
1181 , configSize = \n -> (div n 2 + 3)
1182 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1186 {--------------------------------------------------------------------
1187 Arbitrary, reasonably balanced trees
1188 --------------------------------------------------------------------}
1189 instance Arbitrary a => Arbitrary (IntMap a) where
1190 arbitrary = do{ ks <- arbitrary
1191 ; xs <- mapM (\k -> do{ x <- arbitrary; return (k,x)}) ks
1192 ; return (fromList xs)
1196 {--------------------------------------------------------------------
1197 Single, Insert, Delete
1198 --------------------------------------------------------------------}
1199 prop_Single :: Key -> Int -> Bool
1201 = (insert k x empty == singleton k x)
1203 prop_InsertDelete :: Key -> Int -> IntMap Int -> Property
1204 prop_InsertDelete k x t
1205 = not (member k t) ==> delete k (insert k x t) == t
1207 prop_UpdateDelete :: Key -> IntMap Int -> Bool
1208 prop_UpdateDelete k t
1209 = update (const Nothing) k t == delete k t
1212 {--------------------------------------------------------------------
1214 --------------------------------------------------------------------}
1215 prop_UnionInsert :: Key -> Int -> IntMap Int -> Bool
1216 prop_UnionInsert k x t
1217 = union (singleton k x) t == insert k x t
1219 prop_UnionAssoc :: IntMap Int -> IntMap Int -> IntMap Int -> Bool
1220 prop_UnionAssoc t1 t2 t3
1221 = union t1 (union t2 t3) == union (union t1 t2) t3
1223 prop_UnionComm :: IntMap Int -> IntMap Int -> Bool
1224 prop_UnionComm t1 t2
1225 = (union t1 t2 == unionWith (\x y -> y) t2 t1)
1228 prop_Diff :: [(Key,Int)] -> [(Key,Int)] -> Bool
1230 = List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys)))
1231 == List.sort ((List.\\) (nub (Prelude.map fst xs)) (nub (Prelude.map fst ys)))
1233 prop_Int :: [(Key,Int)] -> [(Key,Int)] -> Bool
1235 = List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys)))
1236 == List.sort (nub ((List.intersect) (Prelude.map fst xs) (Prelude.map fst ys)))
1238 {--------------------------------------------------------------------
1240 --------------------------------------------------------------------}
1242 = forAll (choose (5,100)) $ \n ->
1243 let xs = [(x,()) | x <- [0..n::Int]]
1244 in fromAscList xs == fromList xs
1246 prop_List :: [Key] -> Bool
1248 = (sort (nub xs) == [x | (x,()) <- toAscList (fromList [(x,()) | x <- xs])])