1 {-# OPTIONS_GHC -fno-bang-patterns #-}
3 -----------------------------------------------------------------------------
6 -- Copyright : (c) Daan Leijen 2002
8 -- Maintainer : libraries@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
12 -- An efficient implementation of maps from keys to values (dictionaries).
14 -- Since many function names (but not the type name) clash with
15 -- "Prelude" names, this module is usually imported @qualified@, e.g.
17 -- > import Data.Map (Map)
18 -- > import qualified Data.Map as Map
20 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
21 -- trees of /bounded balance/) as described by:
23 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
24 -- Journal of Functional Programming 3(4):553-562, October 1993,
25 -- <http://www.swiss.ai.mit.edu/~adams/BB>.
27 -- * J. Nievergelt and E.M. Reingold,
28 -- \"/Binary search trees of bounded balance/\",
29 -- SIAM journal of computing 2(1), March 1973.
31 -- Note that the implementation is /left-biased/ -- the elements of a
32 -- first argument are always preferred to the second, for example in
33 -- 'union' or 'insert'.
34 -----------------------------------------------------------------------------
38 Map -- instance Eq,Show,Read
58 , insertWith, insertWithKey, insertLookupWithKey
59 , insertWith', insertWithKey'
120 , fromDistinctAscList
137 , isSubmapOf, isSubmapOfBy
138 , isProperSubmapOf, isProperSubmapOfBy
167 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
168 import qualified Data.Set as Set
169 import qualified Data.List as List
170 import Data.Monoid (Monoid(..))
172 import Control.Applicative (Applicative(..), (<$>))
173 import Data.Traversable (Traversable(traverse))
174 import Data.Foldable (Foldable(foldMap))
178 import qualified Prelude
179 import qualified List
180 import Debug.QuickCheck
181 import List(nub,sort)
184 #if __GLASGOW_HASKELL__
186 import Data.Generics.Basics
187 import Data.Generics.Instances
190 {--------------------------------------------------------------------
192 --------------------------------------------------------------------}
195 -- | /O(log n)/. Find the value at a key.
196 -- Calls 'error' when the element can not be found.
197 (!) :: Ord k => Map k a -> k -> a
200 -- | /O(n+m)/. See 'difference'.
201 (\\) :: Ord k => Map k a -> Map k b -> Map k a
202 m1 \\ m2 = difference m1 m2
204 {--------------------------------------------------------------------
206 --------------------------------------------------------------------}
207 -- | A Map from keys @k@ to values @a@.
209 | Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
213 instance (Ord k) => Monoid (Map k v) where
218 #if __GLASGOW_HASKELL__
220 {--------------------------------------------------------------------
222 --------------------------------------------------------------------}
224 -- This instance preserves data abstraction at the cost of inefficiency.
225 -- We omit reflection services for the sake of data abstraction.
227 instance (Data k, Data a, Ord k) => Data (Map k a) where
228 gfoldl f z map = z fromList `f` (toList map)
229 toConstr _ = error "toConstr"
230 gunfold _ _ = error "gunfold"
231 dataTypeOf _ = mkNorepType "Data.Map.Map"
232 dataCast2 f = gcast2 f
236 {--------------------------------------------------------------------
238 --------------------------------------------------------------------}
239 -- | /O(1)/. Is the map empty?
240 null :: Map k a -> Bool
244 Bin sz k x l r -> False
246 -- | /O(1)/. The number of elements in the map.
247 size :: Map k a -> Int
254 -- | /O(log n)/. Lookup the value at a key in the map.
257 -- @return@ the result in the monad or @fail@ in it the key isn't in the
258 -- map. Often, the monad to use is 'Maybe', so you get either
259 -- @('Just' result)@ or @'Nothing'@.
260 lookup :: (Monad m,Ord k) => k -> Map k a -> m a
261 lookup k t = case lookup' k t of
263 Nothing -> fail "Data.Map.lookup: Key not found"
264 lookup' :: Ord k => k -> Map k a -> Maybe a
269 -> case compare k kx of
274 lookupAssoc :: Ord k => k -> Map k a -> Maybe (k,a)
279 -> case compare k kx of
280 LT -> lookupAssoc k l
281 GT -> lookupAssoc k r
284 -- | /O(log n)/. Is the key a member of the map?
285 member :: Ord k => k -> Map k a -> Bool
291 -- | /O(log n)/. Is the key not a member of the map?
292 notMember :: Ord k => k -> Map k a -> Bool
293 notMember k m = not $ member k m
295 -- | /O(log n)/. Find the value at a key.
296 -- Calls 'error' when the element can not be found.
297 find :: Ord k => k -> Map k a -> a
300 Nothing -> error "Map.find: element not in the map"
303 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
304 -- the value at key @k@ or returns @def@ when the key is not in the map.
305 findWithDefault :: Ord k => a -> k -> Map k a -> a
306 findWithDefault def k m
313 {--------------------------------------------------------------------
315 --------------------------------------------------------------------}
316 -- | /O(1)/. The empty map.
321 -- | /O(1)/. A map with a single element.
322 singleton :: k -> a -> Map k a
326 {--------------------------------------------------------------------
328 --------------------------------------------------------------------}
329 -- | /O(log n)/. Insert a new key and value in the map.
330 -- If the key is already present in the map, the associated value is
331 -- replaced with the supplied value, i.e. 'insert' is equivalent to
332 -- @'insertWith' 'const'@.
333 insert :: Ord k => k -> a -> Map k a -> Map k a
336 Tip -> singleton kx x
338 -> case compare kx ky of
339 LT -> balance ky y (insert kx x l) r
340 GT -> balance ky y l (insert kx x r)
341 EQ -> Bin sz kx x l r
343 -- | /O(log n)/. Insert with a combining function.
344 -- @'insertWith' f key value mp@
345 -- will insert the pair (key, value) into @mp@ if key does
346 -- not exist in the map. If the key does exist, the function will
347 -- insert the pair @(key, f new_value old_value)@.
348 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
350 = insertWithKey (\k x y -> f x y) k x m
352 -- | Same as 'insertWith', but the combining function is applied strictly.
353 insertWith' :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
355 = insertWithKey' (\k x y -> f x y) k x m
358 -- | /O(log n)/. Insert with a combining function.
359 -- @'insertWithKey' 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 key new_value old_value)@.
363 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
364 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
365 insertWithKey f kx x t
367 Tip -> singleton kx x
369 -> case compare kx ky of
370 LT -> balance ky y (insertWithKey f kx x l) r
371 GT -> balance ky y l (insertWithKey f kx x r)
372 EQ -> Bin sy kx (f kx x y) l r
374 -- | Same as 'insertWithKey', but the combining function is applied strictly.
375 insertWithKey' :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
376 insertWithKey' f kx x t
378 Tip -> singleton kx x
380 -> case compare kx ky of
381 LT -> balance ky y (insertWithKey' f kx x l) r
382 GT -> balance ky y l (insertWithKey' f kx x r)
383 EQ -> let x' = f kx x y in seq x' (Bin sy kx x' l r)
386 -- | /O(log n)/. The expression (@'insertLookupWithKey' f k x map@)
387 -- is a pair where the first element is equal to (@'lookup' k map@)
388 -- and the second element equal to (@'insertWithKey' f k x map@).
389 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a,Map k a)
390 insertLookupWithKey f kx x t
392 Tip -> (Nothing, singleton kx x)
394 -> case compare kx ky of
395 LT -> let (found,l') = insertLookupWithKey f kx x l in (found,balance ky y l' r)
396 GT -> let (found,r') = insertLookupWithKey f kx x r in (found,balance ky y l r')
397 EQ -> (Just y, Bin sy kx (f kx x y) l r)
399 {--------------------------------------------------------------------
401 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
402 --------------------------------------------------------------------}
403 -- | /O(log n)/. Delete a key and its value from the map. When the key is not
404 -- a member of the map, the original map is returned.
405 delete :: Ord k => k -> Map k a -> Map k a
410 -> case compare k kx of
411 LT -> balance kx x (delete k l) r
412 GT -> balance kx x l (delete k r)
415 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
416 -- a member of the map, the original map is returned.
417 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
419 = adjustWithKey (\k x -> f x) k m
421 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
422 -- a member of the map, the original map is returned.
423 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
425 = updateWithKey (\k x -> Just (f k x)) k m
427 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
428 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
429 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
430 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
432 = updateWithKey (\k x -> f x) k m
434 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
435 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
436 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
437 -- to the new value @y@.
438 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
443 -> case compare k kx of
444 LT -> balance kx x (updateWithKey f k l) r
445 GT -> balance kx x l (updateWithKey f k r)
447 Just x' -> Bin sx kx x' l r
450 -- | /O(log n)/. Lookup and update.
451 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
452 updateLookupWithKey f k t
456 -> case compare k kx of
457 LT -> let (found,l') = updateLookupWithKey f k l in (found,balance kx x l' r)
458 GT -> let (found,r') = updateLookupWithKey f k r in (found,balance kx x l r')
460 Just x' -> (Just x',Bin sx kx x' l r)
461 Nothing -> (Just x,glue l r)
463 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
464 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
465 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@
466 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
469 Tip -> case f Nothing of
471 Just x -> singleton k x
473 -> case compare k kx of
474 LT -> balance kx x (alter f k l) r
475 GT -> balance kx x l (alter f k r)
476 EQ -> case f (Just x) of
477 Just x' -> Bin sx kx x' l r
480 {--------------------------------------------------------------------
482 --------------------------------------------------------------------}
483 -- | /O(log n)/. Return the /index/ of a key. The index is a number from
484 -- /0/ up to, but not including, the 'size' of the map. Calls 'error' when
485 -- the key is not a 'member' of the map.
486 findIndex :: Ord k => k -> Map k a -> Int
488 = case lookupIndex k t of
489 Nothing -> error "Map.findIndex: element is not in the map"
492 -- | /O(log n)/. Lookup the /index/ of a key. The index is a number from
493 -- /0/ up to, but not including, the 'size' of the map.
494 lookupIndex :: (Monad m,Ord k) => k -> Map k a -> m Int
495 lookupIndex k t = case lookup 0 t of
496 Nothing -> fail "Data.Map.lookupIndex: Key not found."
499 lookup idx Tip = Nothing
500 lookup idx (Bin _ kx x l r)
501 = case compare k kx of
503 GT -> lookup (idx + size l + 1) r
504 EQ -> Just (idx + size l)
506 -- | /O(log n)/. Retrieve an element by /index/. Calls 'error' when an
507 -- invalid index is used.
508 elemAt :: Int -> Map k a -> (k,a)
509 elemAt i Tip = error "Map.elemAt: index out of range"
510 elemAt i (Bin _ kx x l r)
511 = case compare i sizeL of
513 GT -> elemAt (i-sizeL-1) r
518 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
519 -- invalid index is used.
520 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
521 updateAt f i Tip = error "Map.updateAt: index out of range"
522 updateAt f i (Bin sx kx x l r)
523 = case compare i sizeL of
525 GT -> updateAt f (i-sizeL-1) r
527 Just x' -> Bin sx kx x' l r
532 -- | /O(log n)/. Delete the element at /index/.
533 -- Defined as (@'deleteAt' i map = 'updateAt' (\k x -> 'Nothing') i map@).
534 deleteAt :: Int -> Map k a -> Map k a
536 = updateAt (\k x -> Nothing) i map
539 {--------------------------------------------------------------------
541 --------------------------------------------------------------------}
542 -- | /O(log n)/. The minimal key of the map.
543 findMin :: Map k a -> (k,a)
544 findMin (Bin _ kx x Tip r) = (kx,x)
545 findMin (Bin _ kx x l r) = findMin l
546 findMin Tip = error "Map.findMin: empty map has no minimal element"
548 -- | /O(log n)/. The maximal key of the map.
549 findMax :: Map k a -> (k,a)
550 findMax (Bin _ kx x l Tip) = (kx,x)
551 findMax (Bin _ kx x l r) = findMax r
552 findMax Tip = error "Map.findMax: empty map has no maximal element"
554 -- | /O(log n)/. Delete the minimal key.
555 deleteMin :: Map k a -> Map k a
556 deleteMin (Bin _ kx x Tip r) = r
557 deleteMin (Bin _ kx x l r) = balance kx x (deleteMin l) r
560 -- | /O(log n)/. Delete the maximal key.
561 deleteMax :: Map k a -> Map k a
562 deleteMax (Bin _ kx x l Tip) = l
563 deleteMax (Bin _ kx x l r) = balance kx x l (deleteMax r)
566 -- | /O(log n)/. Update the value at the minimal key.
567 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
569 = updateMinWithKey (\k x -> f x) m
571 -- | /O(log n)/. Update the value at the maximal key.
572 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
574 = updateMaxWithKey (\k x -> f x) m
577 -- | /O(log n)/. Update the value at the minimal key.
578 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
581 Bin sx kx x Tip r -> case f kx x of
583 Just x' -> Bin sx kx x' Tip r
584 Bin sx kx x l r -> balance kx x (updateMinWithKey f l) r
587 -- | /O(log n)/. Update the value at the maximal key.
588 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
591 Bin sx kx x l Tip -> case f kx x of
593 Just x' -> Bin sx kx x' l Tip
594 Bin sx kx x l r -> balance kx x l (updateMaxWithKey f r)
597 -- | /O(log n)/. Retrieves the minimal key of the map, and the map stripped from that element
598 -- @fail@s (in the monad) when passed an empty map.
599 minView :: Monad m => Map k a -> m (Map k a, (k,a))
600 minView Tip = fail "Map.minView: empty map"
601 minView x = return (swap $ deleteFindMin x)
603 -- | /O(log n)/. Retrieves the maximal key of the map, and the map stripped from that element
604 -- @fail@s (in the monad) when passed an empty map.
605 maxView :: Monad m => Map k a -> m (Map k a, (k,a))
606 maxView Tip = fail "Map.maxView: empty map"
607 maxView x = return (swap $ deleteFindMax x)
611 {--------------------------------------------------------------------
613 --------------------------------------------------------------------}
614 -- | The union of a list of maps:
615 -- (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
616 unions :: Ord k => [Map k a] -> Map k a
618 = foldlStrict union empty ts
620 -- | The union of a list of maps, with a combining operation:
621 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
622 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
624 = foldlStrict (unionWith f) empty ts
627 -- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
628 -- It prefers @t1@ when duplicate keys are encountered,
629 -- i.e. (@'union' == 'unionWith' 'const'@).
630 -- The implementation uses the efficient /hedge-union/ algorithm.
631 -- Hedge-union is more efficient on (bigset `union` smallset)
632 union :: Ord k => Map k a -> Map k a -> Map k a
635 union t1 t2 = hedgeUnionL (const LT) (const GT) t1 t2
637 -- left-biased hedge union
638 hedgeUnionL cmplo cmphi t1 Tip
640 hedgeUnionL cmplo cmphi Tip (Bin _ kx x l r)
641 = join kx x (filterGt cmplo l) (filterLt cmphi r)
642 hedgeUnionL cmplo cmphi (Bin _ kx x l r) t2
643 = join kx x (hedgeUnionL cmplo cmpkx l (trim cmplo cmpkx t2))
644 (hedgeUnionL cmpkx cmphi r (trim cmpkx cmphi t2))
646 cmpkx k = compare kx k
648 -- right-biased hedge union
649 hedgeUnionR cmplo cmphi t1 Tip
651 hedgeUnionR cmplo cmphi Tip (Bin _ kx x l r)
652 = join kx x (filterGt cmplo l) (filterLt cmphi r)
653 hedgeUnionR cmplo cmphi (Bin _ kx x l r) t2
654 = join kx newx (hedgeUnionR cmplo cmpkx l lt)
655 (hedgeUnionR cmpkx cmphi r gt)
657 cmpkx k = compare kx k
658 lt = trim cmplo cmpkx t2
659 (found,gt) = trimLookupLo kx cmphi t2
664 {--------------------------------------------------------------------
665 Union with a combining function
666 --------------------------------------------------------------------}
667 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
668 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
670 = unionWithKey (\k x y -> f x y) m1 m2
673 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
674 -- Hedge-union is more efficient on (bigset `union` smallset).
675 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
676 unionWithKey f Tip t2 = t2
677 unionWithKey f t1 Tip = t1
678 unionWithKey f t1 t2 = hedgeUnionWithKey f (const LT) (const GT) t1 t2
680 hedgeUnionWithKey f cmplo cmphi t1 Tip
682 hedgeUnionWithKey f cmplo cmphi Tip (Bin _ kx x l r)
683 = join kx x (filterGt cmplo l) (filterLt cmphi r)
684 hedgeUnionWithKey f cmplo cmphi (Bin _ kx x l r) t2
685 = join kx newx (hedgeUnionWithKey f cmplo cmpkx l lt)
686 (hedgeUnionWithKey f cmpkx cmphi r gt)
688 cmpkx k = compare kx k
689 lt = trim cmplo cmpkx t2
690 (found,gt) = trimLookupLo kx cmphi t2
693 Just (_,y) -> f kx x y
695 {--------------------------------------------------------------------
697 --------------------------------------------------------------------}
698 -- | /O(n+m)/. Difference of two maps.
699 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
700 difference :: Ord k => Map k a -> Map k b -> Map k a
701 difference Tip t2 = Tip
702 difference t1 Tip = t1
703 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
705 hedgeDiff cmplo cmphi Tip t
707 hedgeDiff cmplo cmphi (Bin _ kx x l r) Tip
708 = join kx x (filterGt cmplo l) (filterLt cmphi r)
709 hedgeDiff cmplo cmphi t (Bin _ kx x l r)
710 = merge (hedgeDiff cmplo cmpkx (trim cmplo cmpkx t) l)
711 (hedgeDiff cmpkx cmphi (trim cmpkx cmphi t) r)
713 cmpkx k = compare kx k
715 -- | /O(n+m)/. Difference with a combining function.
716 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
717 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
718 differenceWith f m1 m2
719 = differenceWithKey (\k x y -> f x y) m1 m2
721 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
722 -- encountered, the combining function is applied to the key and both values.
723 -- If it returns 'Nothing', the element is discarded (proper set difference). If
724 -- it returns (@'Just' y@), the element is updated with a new value @y@.
725 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
726 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
727 differenceWithKey f Tip t2 = Tip
728 differenceWithKey f t1 Tip = t1
729 differenceWithKey f t1 t2 = hedgeDiffWithKey f (const LT) (const GT) t1 t2
731 hedgeDiffWithKey f cmplo cmphi Tip t
733 hedgeDiffWithKey f cmplo cmphi (Bin _ kx x l r) Tip
734 = join kx x (filterGt cmplo l) (filterLt cmphi r)
735 hedgeDiffWithKey f cmplo cmphi t (Bin _ kx x l r)
737 Nothing -> merge tl tr
740 Nothing -> merge tl tr
741 Just z -> join ky z tl tr
743 cmpkx k = compare kx k
744 lt = trim cmplo cmpkx t
745 (found,gt) = trimLookupLo kx cmphi t
746 tl = hedgeDiffWithKey f cmplo cmpkx lt l
747 tr = hedgeDiffWithKey f cmpkx cmphi gt r
751 {--------------------------------------------------------------------
753 --------------------------------------------------------------------}
754 -- | /O(n+m)/. Intersection of two maps. The values in the first
755 -- map are returned, i.e. (@'intersection' m1 m2 == 'intersectionWith' 'const' m1 m2@).
756 intersection :: Ord k => Map k a -> Map k b -> Map k a
758 = intersectionWithKey (\k x y -> x) m1 m2
760 -- | /O(n+m)/. Intersection with a combining function.
761 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
762 intersectionWith f m1 m2
763 = intersectionWithKey (\k x y -> f x y) m1 m2
765 -- | /O(n+m)/. Intersection with a combining function.
766 -- Intersection is more efficient on (bigset `intersection` smallset)
767 --intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
768 --intersectionWithKey f Tip t = Tip
769 --intersectionWithKey f t Tip = Tip
770 --intersectionWithKey f t1 t2 = intersectWithKey f t1 t2
772 --intersectWithKey f Tip t = Tip
773 --intersectWithKey f t Tip = Tip
774 --intersectWithKey f t (Bin _ kx x l r)
776 -- Nothing -> merge tl tr
777 -- Just y -> join kx (f kx y x) tl tr
779 -- (lt,found,gt) = splitLookup kx t
780 -- tl = intersectWithKey f lt l
781 -- tr = intersectWithKey f gt r
784 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
785 intersectionWithKey f Tip t = Tip
786 intersectionWithKey f t Tip = Tip
787 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
789 let (lt,found,gt) = splitLookupWithKey k2 t1
790 tl = intersectionWithKey f lt l2
791 tr = intersectionWithKey f gt r2
793 Just (k,x) -> join k (f k x x2) tl tr
794 Nothing -> merge tl tr
795 else let (lt,found,gt) = splitLookup k1 t2
796 tl = intersectionWithKey f l1 lt
797 tr = intersectionWithKey f r1 gt
799 Just x -> join k1 (f k1 x1 x) tl tr
800 Nothing -> merge tl tr
804 {--------------------------------------------------------------------
806 --------------------------------------------------------------------}
808 -- This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
809 isSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
811 = isSubmapOfBy (==) m1 m2
814 The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if
815 all keys in @t1@ are in tree @t2@, and when @f@ returns 'True' when
816 applied to their respective values. For example, the following
817 expressions are all 'True':
819 > isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
820 > isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
821 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
823 But the following are all 'False':
825 > isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
826 > isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
827 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
829 isSubmapOfBy :: Ord k => (a->b->Bool) -> Map k a -> Map k b -> Bool
831 = (size t1 <= size t2) && (submap' f t1 t2)
833 submap' f Tip t = True
834 submap' f t Tip = False
835 submap' f (Bin _ kx x l r) t
838 Just y -> f x y && submap' f l lt && submap' f r gt
840 (lt,found,gt) = splitLookup kx t
842 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
843 -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
844 isProperSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
845 isProperSubmapOf m1 m2
846 = isProperSubmapOfBy (==) m1 m2
848 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
849 The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
850 @m1@ and @m2@ are not equal,
851 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
852 applied to their respective values. For example, the following
853 expressions are all 'True':
855 > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
856 > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
858 But the following are all 'False':
860 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
861 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
862 > isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
864 isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool
865 isProperSubmapOfBy f t1 t2
866 = (size t1 < size t2) && (submap' f t1 t2)
868 {--------------------------------------------------------------------
870 --------------------------------------------------------------------}
871 -- | /O(n)/. Filter all values that satisfy the predicate.
872 filter :: Ord k => (a -> Bool) -> Map k a -> Map k a
874 = filterWithKey (\k x -> p x) m
876 -- | /O(n)/. Filter all keys\/values that satisfy the predicate.
877 filterWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> Map k a
878 filterWithKey p Tip = Tip
879 filterWithKey p (Bin _ kx x l r)
880 | p kx x = join kx x (filterWithKey p l) (filterWithKey p r)
881 | otherwise = merge (filterWithKey p l) (filterWithKey p r)
884 -- | /O(n)/. partition the map according to a predicate. The first
885 -- map contains all elements that satisfy the predicate, the second all
886 -- elements that fail the predicate. See also 'split'.
887 partition :: Ord k => (a -> Bool) -> Map k a -> (Map k a,Map k a)
889 = partitionWithKey (\k x -> p x) m
891 -- | /O(n)/. partition the map according to a predicate. The first
892 -- map contains all elements that satisfy the predicate, the second all
893 -- elements that fail the predicate. See also 'split'.
894 partitionWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
895 partitionWithKey p Tip = (Tip,Tip)
896 partitionWithKey p (Bin _ kx x l r)
897 | p kx x = (join kx x l1 r1,merge l2 r2)
898 | otherwise = (merge l1 r1,join kx x l2 r2)
900 (l1,l2) = partitionWithKey p l
901 (r1,r2) = partitionWithKey p r
903 -- | /O(n)/. Map values and collect the 'Just' results.
904 mapMaybe :: Ord k => (a -> Maybe b) -> Map k a -> Map k b
906 = mapMaybeWithKey (\k x -> f x) m
908 -- | /O(n)/. Map keys\/values and collect the 'Just' results.
909 mapMaybeWithKey :: Ord k => (k -> a -> Maybe b) -> Map k a -> Map k b
910 mapMaybeWithKey f Tip = Tip
911 mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
912 Just y -> join kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
913 Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
915 -- | /O(n)/. Map values and separate the 'Left' and 'Right' results.
916 mapEither :: Ord k => (a -> Either b c) -> Map k a -> (Map k b, Map k c)
918 = mapEitherWithKey (\k x -> f x) m
920 -- | /O(n)/. Map keys\/values and separate the 'Left' and 'Right' results.
921 mapEitherWithKey :: Ord k =>
922 (k -> a -> Either b c) -> Map k a -> (Map k b, Map k c)
923 mapEitherWithKey f Tip = (Tip, Tip)
924 mapEitherWithKey f (Bin _ kx x l r) = case f kx x of
925 Left y -> (join kx y l1 r1, merge l2 r2)
926 Right z -> (merge l1 r1, join kx z l2 r2)
928 (l1,l2) = mapEitherWithKey f l
929 (r1,r2) = mapEitherWithKey f r
931 {--------------------------------------------------------------------
933 --------------------------------------------------------------------}
934 -- | /O(n)/. Map a function over all values in the map.
935 map :: (a -> b) -> Map k a -> Map k b
937 = mapWithKey (\k x -> f x) m
939 -- | /O(n)/. Map a function over all values in the map.
940 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
941 mapWithKey f Tip = Tip
942 mapWithKey f (Bin sx kx x l r)
943 = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
945 -- | /O(n)/. The function 'mapAccum' threads an accumulating
946 -- argument through the map in ascending order of keys.
947 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
949 = mapAccumWithKey (\a k x -> f a x) a m
951 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
952 -- argument through the map in ascending order of keys.
953 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
954 mapAccumWithKey f a t
957 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
958 -- argument throught the map in ascending order of keys.
959 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
964 -> let (a1,l') = mapAccumL f a l
966 (a3,r') = mapAccumL f a2 r
967 in (a3,Bin sx kx x' l' r')
969 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
970 -- argument throught the map in descending order of keys.
971 mapAccumR :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
976 -> let (a1,r') = mapAccumR f a r
978 (a3,l') = mapAccumR f a2 l
979 in (a3,Bin sx kx x' l' r')
982 -- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
984 -- The size of the result may be smaller if @f@ maps two or more distinct
985 -- keys to the same new key. In this case the value at the smallest of
986 -- these keys is retained.
988 mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
989 mapKeys = mapKeysWith (\x y->x)
992 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
994 -- The size of the result may be smaller if @f@ maps two or more distinct
995 -- keys to the same new key. In this case the associated values will be
996 -- combined using @c@.
998 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
999 mapKeysWith c f = fromListWith c . List.map fFirst . toList
1000 where fFirst (x,y) = (f x, y)
1004 -- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
1005 -- is strictly monotonic.
1006 -- /The precondition is not checked./
1007 -- Semi-formally, we have:
1009 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
1010 -- > ==> mapKeysMonotonic f s == mapKeys f s
1011 -- > where ls = keys s
1013 mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
1014 mapKeysMonotonic f Tip = Tip
1015 mapKeysMonotonic f (Bin sz k x l r) =
1016 Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
1018 {--------------------------------------------------------------------
1020 --------------------------------------------------------------------}
1022 -- | /O(n)/. Fold the values in the map, such that
1023 -- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
1026 -- > elems map = fold (:) [] map
1028 fold :: (a -> b -> b) -> b -> Map k a -> b
1030 = foldWithKey (\k x z -> f x z) z m
1032 -- | /O(n)/. Fold the keys and values in the map, such that
1033 -- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
1036 -- > keys map = foldWithKey (\k x ks -> k:ks) [] map
1038 foldWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
1042 -- | /O(n)/. In-order fold.
1043 foldi :: (k -> a -> b -> b -> b) -> b -> Map k a -> b
1045 foldi f z (Bin _ kx x l r) = f kx x (foldi f z l) (foldi f z r)
1047 -- | /O(n)/. Post-order fold.
1048 foldr :: (k -> a -> b -> b) -> b -> Map k a -> b
1050 foldr f z (Bin _ kx x l r) = foldr f (f kx x (foldr f z r)) l
1052 -- | /O(n)/. Pre-order fold.
1053 foldl :: (b -> k -> a -> b) -> b -> Map k a -> b
1055 foldl f z (Bin _ kx x l r) = foldl f (f (foldl f z l) kx x) r
1057 {--------------------------------------------------------------------
1059 --------------------------------------------------------------------}
1061 -- Return all elements of the map in the ascending order of their keys.
1062 elems :: Map k a -> [a]
1064 = [x | (k,x) <- assocs m]
1066 -- | /O(n)/. Return all keys of the map in ascending order.
1067 keys :: Map k a -> [k]
1069 = [k | (k,x) <- assocs m]
1071 -- | /O(n)/. The set of all keys of the map.
1072 keysSet :: Map k a -> Set.Set k
1073 keysSet m = Set.fromDistinctAscList (keys m)
1075 -- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
1076 assocs :: Map k a -> [(k,a)]
1080 {--------------------------------------------------------------------
1082 use [foldlStrict] to reduce demand on the control-stack
1083 --------------------------------------------------------------------}
1084 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1085 fromList :: Ord k => [(k,a)] -> Map k a
1087 = foldlStrict ins empty xs
1089 ins t (k,x) = insert k x t
1091 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1092 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1094 = fromListWithKey (\k x y -> f x y) xs
1096 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1097 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1098 fromListWithKey f xs
1099 = foldlStrict ins empty xs
1101 ins t (k,x) = insertWithKey f k x t
1103 -- | /O(n)/. Convert to a list of key\/value pairs.
1104 toList :: Map k a -> [(k,a)]
1105 toList t = toAscList t
1107 -- | /O(n)/. Convert to an ascending list.
1108 toAscList :: Map k a -> [(k,a)]
1109 toAscList t = foldr (\k x xs -> (k,x):xs) [] t
1112 toDescList :: Map k a -> [(k,a)]
1113 toDescList t = foldl (\xs k x -> (k,x):xs) [] t
1116 {--------------------------------------------------------------------
1117 Building trees from ascending/descending lists can be done in linear time.
1119 Note that if [xs] is ascending that:
1120 fromAscList xs == fromList xs
1121 fromAscListWith f xs == fromListWith f xs
1122 --------------------------------------------------------------------}
1123 -- | /O(n)/. Build a map from an ascending list in linear time.
1124 -- /The precondition (input list is ascending) is not checked./
1125 fromAscList :: Eq k => [(k,a)] -> Map k a
1127 = fromAscListWithKey (\k x y -> x) xs
1129 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1130 -- /The precondition (input list is ascending) is not checked./
1131 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1132 fromAscListWith f xs
1133 = fromAscListWithKey (\k x y -> f x y) xs
1135 -- | /O(n)/. Build a map from an ascending list in linear time with a
1136 -- combining function for equal keys.
1137 -- /The precondition (input list is ascending) is not checked./
1138 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1139 fromAscListWithKey f xs
1140 = fromDistinctAscList (combineEq f xs)
1142 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1147 (x:xx) -> combineEq' x xx
1149 combineEq' z [] = [z]
1150 combineEq' z@(kz,zz) (x@(kx,xx):xs)
1151 | kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs
1152 | otherwise = z:combineEq' x xs
1155 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1156 -- /The precondition is not checked./
1157 fromDistinctAscList :: [(k,a)] -> Map k a
1158 fromDistinctAscList xs
1159 = build const (length xs) xs
1161 -- 1) use continutations so that we use heap space instead of stack space.
1162 -- 2) special case for n==5 to build bushier trees.
1163 build c 0 xs = c Tip xs
1164 build c 5 xs = case xs of
1165 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1166 -> c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3)) (singleton k5 x5)) xx
1167 build c n xs = seq nr $ build (buildR nr c) nl xs
1172 buildR n c l ((k,x):ys) = build (buildB l k x c) n ys
1173 buildB l k x c r zs = c (bin k x l r) zs
1177 {--------------------------------------------------------------------
1178 Utility functions that return sub-ranges of the original
1179 tree. Some functions take a comparison function as argument to
1180 allow comparisons against infinite values. A function [cmplo k]
1181 should be read as [compare lo k].
1183 [trim cmplo cmphi t] A tree that is either empty or where [cmplo k == LT]
1184 and [cmphi k == GT] for the key [k] of the root.
1185 [filterGt cmp t] A tree where for all keys [k]. [cmp k == LT]
1186 [filterLt cmp t] A tree where for all keys [k]. [cmp k == GT]
1188 [split k t] Returns two trees [l] and [r] where all keys
1189 in [l] are <[k] and all keys in [r] are >[k].
1190 [splitLookup k t] Just like [split] but also returns whether [k]
1191 was found in the tree.
1192 --------------------------------------------------------------------}
1194 {--------------------------------------------------------------------
1195 [trim lo hi t] trims away all subtrees that surely contain no
1196 values between the range [lo] to [hi]. The returned tree is either
1197 empty or the key of the root is between @lo@ and @hi@.
1198 --------------------------------------------------------------------}
1199 trim :: (k -> Ordering) -> (k -> Ordering) -> Map k a -> Map k a
1200 trim cmplo cmphi Tip = Tip
1201 trim cmplo cmphi t@(Bin sx kx x l r)
1203 LT -> case cmphi kx of
1205 le -> trim cmplo cmphi l
1206 ge -> trim cmplo cmphi r
1208 trimLookupLo :: Ord k => k -> (k -> Ordering) -> Map k a -> (Maybe (k,a), Map k a)
1209 trimLookupLo lo cmphi Tip = (Nothing,Tip)
1210 trimLookupLo lo cmphi t@(Bin sx kx x l r)
1211 = case compare lo kx of
1212 LT -> case cmphi kx of
1213 GT -> (lookupAssoc lo t, t)
1214 le -> trimLookupLo lo cmphi l
1215 GT -> trimLookupLo lo cmphi r
1216 EQ -> (Just (kx,x),trim (compare lo) cmphi r)
1219 {--------------------------------------------------------------------
1220 [filterGt k t] filter all keys >[k] from tree [t]
1221 [filterLt k t] filter all keys <[k] from tree [t]
1222 --------------------------------------------------------------------}
1223 filterGt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1224 filterGt cmp Tip = Tip
1225 filterGt cmp (Bin sx kx x l r)
1227 LT -> join kx x (filterGt cmp l) r
1228 GT -> filterGt cmp r
1231 filterLt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1232 filterLt cmp Tip = Tip
1233 filterLt cmp (Bin sx kx x l r)
1235 LT -> filterLt cmp l
1236 GT -> join kx x l (filterLt cmp r)
1239 {--------------------------------------------------------------------
1241 --------------------------------------------------------------------}
1242 -- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@ where
1243 -- the keys in @map1@ are smaller than @k@ and the keys in @map2@ larger than @k@. Any key equal to @k@ is found in neither @map1@ nor @map2@.
1244 split :: Ord k => k -> Map k a -> (Map k a,Map k a)
1245 split k Tip = (Tip,Tip)
1246 split k (Bin sx kx x l r)
1247 = case compare k kx of
1248 LT -> let (lt,gt) = split k l in (lt,join kx x gt r)
1249 GT -> let (lt,gt) = split k r in (join kx x l lt,gt)
1252 -- | /O(log n)/. The expression (@'splitLookup' k map@) splits a map just
1253 -- like 'split' but also returns @'lookup' k map@.
1254 splitLookup :: Ord k => k -> Map k a -> (Map k a,Maybe a,Map k a)
1255 splitLookup k Tip = (Tip,Nothing,Tip)
1256 splitLookup k (Bin sx kx x l r)
1257 = case compare k kx of
1258 LT -> let (lt,z,gt) = splitLookup k l in (lt,z,join kx x gt r)
1259 GT -> let (lt,z,gt) = splitLookup k r in (join kx x l lt,z,gt)
1263 splitLookupWithKey :: Ord k => k -> Map k a -> (Map k a,Maybe (k,a),Map k a)
1264 splitLookupWithKey k Tip = (Tip,Nothing,Tip)
1265 splitLookupWithKey k (Bin sx kx x l r)
1266 = case compare k kx of
1267 LT -> let (lt,z,gt) = splitLookupWithKey k l in (lt,z,join kx x gt r)
1268 GT -> let (lt,z,gt) = splitLookupWithKey k r in (join kx x l lt,z,gt)
1269 EQ -> (l,Just (kx, x),r)
1271 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
1272 -- element was found in the original set.
1273 splitMember :: Ord k => k -> Map k a -> (Map k a,Bool,Map k a)
1274 splitMember x t = let (l,m,r) = splitLookup x t in
1275 (l,maybe False (const True) m,r)
1278 {--------------------------------------------------------------------
1279 Utility functions that maintain the balance properties of the tree.
1280 All constructors assume that all values in [l] < [k] and all values
1281 in [r] > [k], and that [l] and [r] are valid trees.
1283 In order of sophistication:
1284 [Bin sz k x l r] The type constructor.
1285 [bin k x l r] Maintains the correct size, assumes that both [l]
1286 and [r] are balanced with respect to each other.
1287 [balance k x l r] Restores the balance and size.
1288 Assumes that the original tree was balanced and
1289 that [l] or [r] has changed by at most one element.
1290 [join k x l r] Restores balance and size.
1292 Furthermore, we can construct a new tree from two trees. Both operations
1293 assume that all values in [l] < all values in [r] and that [l] and [r]
1295 [glue l r] Glues [l] and [r] together. Assumes that [l] and
1296 [r] are already balanced with respect to each other.
1297 [merge l r] Merges two trees and restores balance.
1299 Note: in contrast to Adam's paper, we use (<=) comparisons instead
1300 of (<) comparisons in [join], [merge] and [balance].
1301 Quickcheck (on [difference]) showed that this was necessary in order
1302 to maintain the invariants. It is quite unsatisfactory that I haven't
1303 been able to find out why this is actually the case! Fortunately, it
1304 doesn't hurt to be a bit more conservative.
1305 --------------------------------------------------------------------}
1307 {--------------------------------------------------------------------
1309 --------------------------------------------------------------------}
1310 join :: Ord k => k -> a -> Map k a -> Map k a -> Map k a
1311 join kx x Tip r = insertMin kx x r
1312 join kx x l Tip = insertMax kx x l
1313 join kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
1314 | delta*sizeL <= sizeR = balance kz z (join kx x l lz) rz
1315 | delta*sizeR <= sizeL = balance ky y ly (join kx x ry r)
1316 | otherwise = bin kx x l r
1319 -- insertMin and insertMax don't perform potentially expensive comparisons.
1320 insertMax,insertMin :: k -> a -> Map k a -> Map k a
1323 Tip -> singleton kx x
1325 -> balance ky y l (insertMax kx x r)
1329 Tip -> singleton kx x
1331 -> balance ky y (insertMin kx x l) r
1333 {--------------------------------------------------------------------
1334 [merge l r]: merges two trees.
1335 --------------------------------------------------------------------}
1336 merge :: Map k a -> Map k a -> Map k a
1339 merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
1340 | delta*sizeL <= sizeR = balance ky y (merge l ly) ry
1341 | delta*sizeR <= sizeL = balance kx x lx (merge rx r)
1342 | otherwise = glue l r
1344 {--------------------------------------------------------------------
1345 [glue l r]: glues two trees together.
1346 Assumes that [l] and [r] are already balanced with respect to each other.
1347 --------------------------------------------------------------------}
1348 glue :: Map k a -> Map k a -> Map k a
1352 | size l > size r = let ((km,m),l') = deleteFindMax l in balance km m l' r
1353 | otherwise = let ((km,m),r') = deleteFindMin r in balance km m l r'
1356 -- | /O(log n)/. Delete and find the minimal element.
1357 deleteFindMin :: Map k a -> ((k,a),Map k a)
1360 Bin _ k x Tip r -> ((k,x),r)
1361 Bin _ k x l r -> let (km,l') = deleteFindMin l in (km,balance k x l' r)
1362 Tip -> (error "Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
1364 -- | /O(log n)/. Delete and find the maximal element.
1365 deleteFindMax :: Map k a -> ((k,a),Map k a)
1368 Bin _ k x l Tip -> ((k,x),l)
1369 Bin _ k x l r -> let (km,r') = deleteFindMax r in (km,balance k x l r')
1370 Tip -> (error "Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
1373 {--------------------------------------------------------------------
1374 [balance l x r] balances two trees with value x.
1375 The sizes of the trees should balance after decreasing the
1376 size of one of them. (a rotation).
1378 [delta] is the maximal relative difference between the sizes of
1379 two trees, it corresponds with the [w] in Adams' paper.
1380 [ratio] is the ratio between an outer and inner sibling of the
1381 heavier subtree in an unbalanced setting. It determines
1382 whether a double or single rotation should be performed
1383 to restore balance. It is correspondes with the inverse
1384 of $\alpha$ in Adam's article.
1387 - [delta] should be larger than 4.646 with a [ratio] of 2.
1388 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
1390 - A lower [delta] leads to a more 'perfectly' balanced tree.
1391 - A higher [delta] performs less rebalancing.
1393 - Balancing is automatic for random data and a balancing
1394 scheme is only necessary to avoid pathological worst cases.
1395 Almost any choice will do, and in practice, a rather large
1396 [delta] may perform better than smaller one.
1398 Note: in contrast to Adam's paper, we use a ratio of (at least) [2]
1399 to decide whether a single or double rotation is needed. Allthough
1400 he actually proves that this ratio is needed to maintain the
1401 invariants, his implementation uses an invalid ratio of [1].
1402 --------------------------------------------------------------------}
1407 balance :: k -> a -> Map k a -> Map k a -> Map k a
1409 | sizeL + sizeR <= 1 = Bin sizeX k x l r
1410 | sizeR >= delta*sizeL = rotateL k x l r
1411 | sizeL >= delta*sizeR = rotateR k x l r
1412 | otherwise = Bin sizeX k x l r
1416 sizeX = sizeL + sizeR + 1
1419 rotateL k x l r@(Bin _ _ _ ly ry)
1420 | size ly < ratio*size ry = singleL k x l r
1421 | otherwise = doubleL k x l r
1423 rotateR k x l@(Bin _ _ _ ly ry) r
1424 | size ry < ratio*size ly = singleR k x l r
1425 | otherwise = doubleR k x l r
1428 singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
1429 singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
1431 doubleL k1 x1 t1 (Bin _ k2 x2 (Bin _ k3 x3 t2 t3) t4) = bin k3 x3 (bin k1 x1 t1 t2) (bin k2 x2 t3 t4)
1432 doubleR k1 x1 (Bin _ k2 x2 t1 (Bin _ k3 x3 t2 t3)) t4 = bin k3 x3 (bin k2 x2 t1 t2) (bin k1 x1 t3 t4)
1435 {--------------------------------------------------------------------
1436 The bin constructor maintains the size of the tree
1437 --------------------------------------------------------------------}
1438 bin :: k -> a -> Map k a -> Map k a -> Map k a
1440 = Bin (size l + size r + 1) k x l r
1443 {--------------------------------------------------------------------
1444 Eq converts the tree to a list. In a lazy setting, this
1445 actually seems one of the faster methods to compare two trees
1446 and it is certainly the simplest :-)
1447 --------------------------------------------------------------------}
1448 instance (Eq k,Eq a) => Eq (Map k a) where
1449 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
1451 {--------------------------------------------------------------------
1453 --------------------------------------------------------------------}
1455 instance (Ord k, Ord v) => Ord (Map k v) where
1456 compare m1 m2 = compare (toAscList m1) (toAscList m2)
1458 {--------------------------------------------------------------------
1460 --------------------------------------------------------------------}
1461 instance Functor (Map k) where
1464 instance Traversable (Map k) where
1465 traverse f Tip = pure Tip
1466 traverse f (Bin s k v l r)
1467 = flip (Bin s k) <$> traverse f l <*> f v <*> traverse f r
1469 instance Foldable (Map k) where
1470 foldMap _f Tip = mempty
1471 foldMap f (Bin _s _k v l r)
1472 = foldMap f l `mappend` f v `mappend` foldMap f r
1474 {--------------------------------------------------------------------
1476 --------------------------------------------------------------------}
1477 instance (Ord k, Read k, Read e) => Read (Map k e) where
1478 #ifdef __GLASGOW_HASKELL__
1479 readPrec = parens $ prec 10 $ do
1480 Ident "fromList" <- lexP
1482 return (fromList xs)
1484 readListPrec = readListPrecDefault
1486 readsPrec p = readParen (p > 10) $ \ r -> do
1487 ("fromList",s) <- lex r
1489 return (fromList xs,t)
1492 -- parses a pair of things with the syntax a:=b
1493 readPair :: (Read a, Read b) => ReadS (a,b)
1494 readPair s = do (a, ct1) <- reads s
1495 (":=", ct2) <- lex ct1
1496 (b, ct3) <- reads ct2
1499 {--------------------------------------------------------------------
1501 --------------------------------------------------------------------}
1502 instance (Show k, Show a) => Show (Map k a) where
1503 showsPrec d m = showParen (d > 10) $
1504 showString "fromList " . shows (toList m)
1506 showMap :: (Show k,Show a) => [(k,a)] -> ShowS
1510 = showChar '{' . showElem x . showTail xs
1512 showTail [] = showChar '}'
1513 showTail (x:xs) = showString ", " . showElem x . showTail xs
1515 showElem (k,x) = shows k . showString " := " . shows x
1518 -- | /O(n)/. Show the tree that implements the map. The tree is shown
1519 -- in a compressed, hanging format.
1520 showTree :: (Show k,Show a) => Map k a -> String
1522 = showTreeWith showElem True False m
1524 showElem k x = show k ++ ":=" ++ show x
1527 {- | /O(n)/. The expression (@'showTreeWith' showelem hang wide map@) shows
1528 the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
1529 'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
1530 @wide@ is 'True', an extra wide version is shown.
1532 > Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]]
1533 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t
1540 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t
1551 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t
1563 showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
1564 showTreeWith showelem hang wide t
1565 | hang = (showsTreeHang showelem wide [] t) ""
1566 | otherwise = (showsTree showelem wide [] [] t) ""
1568 showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
1569 showsTree showelem wide lbars rbars t
1571 Tip -> showsBars lbars . showString "|\n"
1573 -> showsBars lbars . showString (showelem kx x) . showString "\n"
1575 -> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
1576 showWide wide rbars .
1577 showsBars lbars . showString (showelem kx x) . showString "\n" .
1578 showWide wide lbars .
1579 showsTree showelem wide (withEmpty lbars) (withBar lbars) l
1581 showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
1582 showsTreeHang showelem wide bars t
1584 Tip -> showsBars bars . showString "|\n"
1586 -> showsBars bars . showString (showelem kx x) . showString "\n"
1588 -> showsBars bars . showString (showelem kx x) . showString "\n" .
1589 showWide wide bars .
1590 showsTreeHang showelem wide (withBar bars) l .
1591 showWide wide bars .
1592 showsTreeHang showelem wide (withEmpty bars) r
1596 | wide = showString (concat (reverse bars)) . showString "|\n"
1599 showsBars :: [String] -> ShowS
1603 _ -> showString (concat (reverse (tail bars))) . showString node
1606 withBar bars = "| ":bars
1607 withEmpty bars = " ":bars
1609 {--------------------------------------------------------------------
1611 --------------------------------------------------------------------}
1613 #include "Typeable.h"
1614 INSTANCE_TYPEABLE2(Map,mapTc,"Map")
1616 {--------------------------------------------------------------------
1618 --------------------------------------------------------------------}
1619 -- | /O(n)/. Test if the internal map structure is valid.
1620 valid :: Ord k => Map k a -> Bool
1622 = balanced t && ordered t && validsize t
1625 = bounded (const True) (const True) t
1630 Bin sz kx x l r -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
1632 -- | Exported only for "Debug.QuickCheck"
1633 balanced :: Map k a -> Bool
1637 Bin sz kx x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1638 balanced l && balanced r
1642 = (realsize t == Just (size t))
1647 Bin sz kx x l r -> case (realsize l,realsize r) of
1648 (Just n,Just m) | n+m+1 == sz -> Just sz
1651 {--------------------------------------------------------------------
1653 --------------------------------------------------------------------}
1657 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
1661 {--------------------------------------------------------------------
1663 --------------------------------------------------------------------}
1664 testTree xs = fromList [(x,"*") | x <- xs]
1665 test1 = testTree [1..20]
1666 test2 = testTree [30,29..10]
1667 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1669 {--------------------------------------------------------------------
1671 --------------------------------------------------------------------}
1676 { configMaxTest = 500
1677 , configMaxFail = 5000
1678 , configSize = \n -> (div n 2 + 3)
1679 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1683 {--------------------------------------------------------------------
1684 Arbitrary, reasonably balanced trees
1685 --------------------------------------------------------------------}
1686 instance (Enum k,Arbitrary a) => Arbitrary (Map k a) where
1687 arbitrary = sized (arbtree 0 maxkey)
1688 where maxkey = 10000
1690 arbtree :: (Enum k,Arbitrary a) => Int -> Int -> Int -> Gen (Map k a)
1692 | n <= 0 = return Tip
1693 | lo >= hi = return Tip
1694 | otherwise = do{ x <- arbitrary
1695 ; i <- choose (lo,hi)
1696 ; m <- choose (1,30)
1697 ; let (ml,mr) | m==(1::Int)= (1,2)
1701 ; l <- arbtree lo (i-1) (n `div` ml)
1702 ; r <- arbtree (i+1) hi (n `div` mr)
1703 ; return (bin (toEnum i) x l r)
1707 {--------------------------------------------------------------------
1709 --------------------------------------------------------------------}
1710 forValid :: (Show k,Enum k,Show a,Arbitrary a,Testable b) => (Map k a -> b) -> Property
1712 = forAll arbitrary $ \t ->
1713 -- classify (balanced t) "balanced" $
1714 classify (size t == 0) "empty" $
1715 classify (size t > 0 && size t <= 10) "small" $
1716 classify (size t > 10 && size t <= 64) "medium" $
1717 classify (size t > 64) "large" $
1720 forValidIntTree :: Testable a => (Map Int Int -> a) -> Property
1724 forValidUnitTree :: Testable a => (Map Int () -> a) -> Property
1730 = forValidUnitTree $ \t -> valid t
1732 {--------------------------------------------------------------------
1733 Single, Insert, Delete
1734 --------------------------------------------------------------------}
1735 prop_Single :: Int -> Int -> Bool
1737 = (insert k x empty == singleton k x)
1739 prop_InsertValid :: Int -> Property
1741 = forValidUnitTree $ \t -> valid (insert k () t)
1743 prop_InsertDelete :: Int -> Map Int () -> Property
1744 prop_InsertDelete k t
1745 = (lookup k t == Nothing) ==> delete k (insert k () t) == t
1747 prop_DeleteValid :: Int -> Property
1749 = forValidUnitTree $ \t ->
1750 valid (delete k (insert k () t))
1752 {--------------------------------------------------------------------
1754 --------------------------------------------------------------------}
1755 prop_Join :: Int -> Property
1757 = forValidUnitTree $ \t ->
1758 let (l,r) = split k t
1759 in valid (join k () l r)
1761 prop_Merge :: Int -> Property
1763 = forValidUnitTree $ \t ->
1764 let (l,r) = split k t
1765 in valid (merge l r)
1768 {--------------------------------------------------------------------
1770 --------------------------------------------------------------------}
1771 prop_UnionValid :: Property
1773 = forValidUnitTree $ \t1 ->
1774 forValidUnitTree $ \t2 ->
1777 prop_UnionInsert :: Int -> Int -> Map Int Int -> Bool
1778 prop_UnionInsert k x t
1779 = union (singleton k x) t == insert k x t
1781 prop_UnionAssoc :: Map Int Int -> Map Int Int -> Map Int Int -> Bool
1782 prop_UnionAssoc t1 t2 t3
1783 = union t1 (union t2 t3) == union (union t1 t2) t3
1785 prop_UnionComm :: Map Int Int -> Map Int Int -> Bool
1786 prop_UnionComm t1 t2
1787 = (union t1 t2 == unionWith (\x y -> y) t2 t1)
1790 = forValidIntTree $ \t1 ->
1791 forValidIntTree $ \t2 ->
1792 valid (unionWithKey (\k x y -> x+y) t1 t2)
1794 prop_UnionWith :: [(Int,Int)] -> [(Int,Int)] -> Bool
1795 prop_UnionWith xs ys
1796 = sum (elems (unionWith (+) (fromListWith (+) xs) (fromListWith (+) ys)))
1797 == (sum (Prelude.map snd xs) + sum (Prelude.map snd ys))
1800 = forValidUnitTree $ \t1 ->
1801 forValidUnitTree $ \t2 ->
1802 valid (difference t1 t2)
1804 prop_Diff :: [(Int,Int)] -> [(Int,Int)] -> Bool
1806 = List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys)))
1807 == List.sort ((List.\\) (nub (Prelude.map fst xs)) (nub (Prelude.map fst ys)))
1810 = forValidUnitTree $ \t1 ->
1811 forValidUnitTree $ \t2 ->
1812 valid (intersection t1 t2)
1814 prop_Int :: [(Int,Int)] -> [(Int,Int)] -> Bool
1816 = List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys)))
1817 == List.sort (nub ((List.intersect) (Prelude.map fst xs) (Prelude.map fst ys)))
1819 {--------------------------------------------------------------------
1821 --------------------------------------------------------------------}
1823 = forAll (choose (5,100)) $ \n ->
1824 let xs = [(x,()) | x <- [0..n::Int]]
1825 in fromAscList xs == fromList xs
1827 prop_List :: [Int] -> Bool
1829 = (sort (nub xs) == [x | (x,()) <- toList (fromList [(x,()) | x <- xs])])