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 -- This module is intended to be imported @qualified@, to avoid name
15 -- clashes with Prelude functions. eg.
17 -- > import Data.Map as Map
19 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
20 -- trees of /bounded balance/) as described by:
22 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
23 -- Journal of Functional Programming 3(4):553-562, October 1993,
24 -- <http://www.swiss.ai.mit.edu/~adams/BB>.
26 -- * J. Nievergelt and E.M. Reingold,
27 -- \"/Binary search trees of bounded balance/\",
28 -- SIAM journal of computing 2(1), March 1973.
30 -- Note that the implementation is /left-biased/ -- the elements of a
31 -- first argument are always preferred to the second, for example in
32 -- 'union' or 'insert'.
33 -----------------------------------------------------------------------------
37 Map -- instance Eq,Show,Read
57 , insertWith, insertWithKey, insertLookupWithKey
118 , fromDistinctAscList
130 , isSubmapOf, isSubmapOfBy
131 , isProperSubmapOf, isProperSubmapOfBy
160 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
161 import qualified Data.Set as Set
162 import qualified Data.List as List
163 import Data.Monoid (Monoid(..))
165 import Control.Applicative (Applicative(..), (<$>))
166 import Data.Traversable (Traversable(traverse))
167 import Data.Foldable (Foldable(foldMap))
171 import qualified Prelude
172 import qualified List
173 import Debug.QuickCheck
174 import List(nub,sort)
177 #if __GLASGOW_HASKELL__
179 import Data.Generics.Basics
180 import Data.Generics.Instances
183 {--------------------------------------------------------------------
185 --------------------------------------------------------------------}
188 -- | /O(log n)/. Find the value at a key.
189 -- Calls 'error' when the element can not be found.
190 (!) :: Ord k => Map k a -> k -> a
193 -- | /O(n+m)/. See 'difference'.
194 (\\) :: Ord k => Map k a -> Map k b -> Map k a
195 m1 \\ m2 = difference m1 m2
197 {--------------------------------------------------------------------
199 --------------------------------------------------------------------}
200 -- | A Map from keys @k@ to values @a@.
202 | Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
206 instance (Ord k) => Monoid (Map k v) where
211 #if __GLASGOW_HASKELL__
213 {--------------------------------------------------------------------
215 --------------------------------------------------------------------}
217 -- This instance preserves data abstraction at the cost of inefficiency.
218 -- We omit reflection services for the sake of data abstraction.
220 instance (Data k, Data a, Ord k) => Data (Map k a) where
221 gfoldl f z map = z fromList `f` (toList map)
222 toConstr _ = error "toConstr"
223 gunfold _ _ = error "gunfold"
224 dataTypeOf _ = mkNorepType "Data.Map.Map"
225 dataCast2 f = gcast2 f
229 {--------------------------------------------------------------------
231 --------------------------------------------------------------------}
232 -- | /O(1)/. Is the map empty?
233 null :: Map k a -> Bool
237 Bin sz k x l r -> False
239 -- | /O(1)/. The number of elements in the map.
240 size :: Map k a -> Int
247 -- | /O(log n)/. Lookup the value at a key in the map.
248 lookup :: (Monad m,Ord k) => k -> Map k a -> m a
249 lookup k t = case lookup' k t of
251 Nothing -> fail "Data.Map.lookup: Key not found"
252 lookup' :: Ord k => k -> Map k a -> Maybe a
257 -> case compare k kx of
262 lookupAssoc :: Ord k => k -> Map k a -> Maybe (k,a)
267 -> case compare k kx of
268 LT -> lookupAssoc k l
269 GT -> lookupAssoc k r
272 -- | /O(log n)/. Is the key a member of the map?
273 member :: Ord k => k -> Map k a -> Bool
279 -- | /O(log n)/. Is the key not a member of the map?
280 notMember :: Ord k => k -> Map k a -> Bool
281 notMember k m = not $ member k m
283 -- | /O(log n)/. Find the value at a key.
284 -- Calls 'error' when the element can not be found.
285 find :: Ord k => k -> Map k a -> a
288 Nothing -> error "Map.find: element not in the map"
291 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
292 -- the value at key @k@ or returns @def@ when the key is not in the map.
293 findWithDefault :: Ord k => a -> k -> Map k a -> a
294 findWithDefault def k m
301 {--------------------------------------------------------------------
303 --------------------------------------------------------------------}
304 -- | /O(1)/. The empty map.
309 -- | /O(1)/. A map with a single element.
310 singleton :: k -> a -> Map k a
314 {--------------------------------------------------------------------
316 --------------------------------------------------------------------}
317 -- | /O(log n)/. Insert a new key and value in the map.
318 -- If the key is already present in the map, the associated value is
319 -- replaced with the supplied value, i.e. 'insert' is equivalent to
320 -- @'insertWith' 'const'@.
321 insert :: Ord k => k -> a -> Map k a -> Map k a
324 Tip -> singleton kx x
326 -> case compare kx ky of
327 LT -> balance ky y (insert kx x l) r
328 GT -> balance ky y l (insert kx x r)
329 EQ -> Bin sz kx x l r
331 -- | /O(log n)/. Insert with a combining function.
332 -- @'insertWith' f key value mp@
333 -- will insert the pair (key, value) into @mp@ if key does
334 -- not exist in the map. If the key does exist, the function will
335 -- insert the pair @(key, f new_value old_value)@.
336 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
338 = insertWithKey (\k x y -> f x y) k x m
340 -- | /O(log n)/. Insert with a combining function.
341 -- @'insertWithKey' f key value mp@
342 -- will insert the pair (key, value) into @mp@ if key does
343 -- not exist in the map. If the key does exist, the function will
344 -- insert the pair @(key,f key new_value old_value)@.
345 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
346 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
347 insertWithKey f kx x t
349 Tip -> singleton kx x
351 -> case compare kx ky of
352 LT -> balance ky y (insertWithKey f kx x l) r
353 GT -> balance ky y l (insertWithKey f kx x r)
354 EQ -> Bin sy kx (f kx x y) l r
356 -- | /O(log n)/. The expression (@'insertLookupWithKey' f k x map@)
357 -- is a pair where the first element is equal to (@'lookup' k map@)
358 -- and the second element equal to (@'insertWithKey' f k x map@).
359 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a,Map k a)
360 insertLookupWithKey f kx x t
362 Tip -> (Nothing, singleton kx x)
364 -> case compare kx ky of
365 LT -> let (found,l') = insertLookupWithKey f kx x l in (found,balance ky y l' r)
366 GT -> let (found,r') = insertLookupWithKey f kx x r in (found,balance ky y l r')
367 EQ -> (Just y, Bin sy kx (f kx x y) l r)
369 {--------------------------------------------------------------------
371 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
372 --------------------------------------------------------------------}
373 -- | /O(log n)/. Delete a key and its value from the map. When the key is not
374 -- a member of the map, the original map is returned.
375 delete :: Ord k => k -> Map k a -> Map k a
380 -> case compare k kx of
381 LT -> balance kx x (delete k l) r
382 GT -> balance kx x l (delete k r)
385 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
386 -- a member of the map, the original map is returned.
387 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
389 = adjustWithKey (\k x -> f x) k m
391 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
392 -- a member of the map, the original map is returned.
393 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
395 = updateWithKey (\k x -> Just (f k x)) k m
397 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
398 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
399 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
400 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
402 = updateWithKey (\k x -> f x) k m
404 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
405 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
406 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
407 -- to the new value @y@.
408 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
413 -> case compare k kx of
414 LT -> balance kx x (updateWithKey f k l) r
415 GT -> balance kx x l (updateWithKey f k r)
417 Just x' -> Bin sx kx x' l r
420 -- | /O(log n)/. Lookup and update.
421 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
422 updateLookupWithKey f k t
426 -> case compare k kx of
427 LT -> let (found,l') = updateLookupWithKey f k l in (found,balance kx x l' r)
428 GT -> let (found,r') = updateLookupWithKey f k r in (found,balance kx x l r')
430 Just x' -> (Just x',Bin sx kx x' l r)
431 Nothing -> (Just x,glue l r)
433 -- | /O(log n)/. The expression (@'alter' f k map@) alters the value @x@ at @k@, or absence thereof.
434 -- 'alter' can be used to insert, delete, or update a value in a 'Map'.
435 -- In short : @'lookup' k ('alter' f k m) = f ('lookup' k m)@
436 alter :: Ord k => (Maybe a -> Maybe a) -> k -> Map k a -> Map k a
439 Tip -> case f Nothing of
441 Just x -> singleton k x
443 -> case compare k kx of
444 LT -> balance kx x (alter f k l) r
445 GT -> balance kx x l (alter f k r)
446 EQ -> case f (Just x) of
447 Just x' -> Bin sx kx x' l r
450 {--------------------------------------------------------------------
452 --------------------------------------------------------------------}
453 -- | /O(log n)/. Return the /index/ of a key. The index is a number from
454 -- /0/ up to, but not including, the 'size' of the map. Calls 'error' when
455 -- the key is not a 'member' of the map.
456 findIndex :: Ord k => k -> Map k a -> Int
458 = case lookupIndex k t of
459 Nothing -> error "Map.findIndex: element is not in the map"
462 -- | /O(log n)/. Lookup the /index/ of a key. The index is a number from
463 -- /0/ up to, but not including, the 'size' of the map.
464 lookupIndex :: (Monad m,Ord k) => k -> Map k a -> m Int
465 lookupIndex k t = case lookup 0 t of
466 Nothing -> fail "Data.Map.lookupIndex: Key not found."
469 lookup idx Tip = Nothing
470 lookup idx (Bin _ kx x l r)
471 = case compare k kx of
473 GT -> lookup (idx + size l + 1) r
474 EQ -> Just (idx + size l)
476 -- | /O(log n)/. Retrieve an element by /index/. Calls 'error' when an
477 -- invalid index is used.
478 elemAt :: Int -> Map k a -> (k,a)
479 elemAt i Tip = error "Map.elemAt: index out of range"
480 elemAt i (Bin _ kx x l r)
481 = case compare i sizeL of
483 GT -> elemAt (i-sizeL-1) r
488 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
489 -- invalid index is used.
490 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
491 updateAt f i Tip = error "Map.updateAt: index out of range"
492 updateAt f i (Bin sx kx x l r)
493 = case compare i sizeL of
495 GT -> updateAt f (i-sizeL-1) r
497 Just x' -> Bin sx kx x' l r
502 -- | /O(log n)/. Delete the element at /index/.
503 -- Defined as (@'deleteAt' i map = 'updateAt' (\k x -> 'Nothing') i map@).
504 deleteAt :: Int -> Map k a -> Map k a
506 = updateAt (\k x -> Nothing) i map
509 {--------------------------------------------------------------------
511 --------------------------------------------------------------------}
512 -- | /O(log n)/. The minimal key of the map.
513 findMin :: Map k a -> (k,a)
514 findMin (Bin _ kx x Tip r) = (kx,x)
515 findMin (Bin _ kx x l r) = findMin l
516 findMin Tip = error "Map.findMin: empty map has no minimal element"
518 -- | /O(log n)/. The maximal key of the map.
519 findMax :: Map k a -> (k,a)
520 findMax (Bin _ kx x l Tip) = (kx,x)
521 findMax (Bin _ kx x l r) = findMax r
522 findMax Tip = error "Map.findMax: empty map has no maximal element"
524 -- | /O(log n)/. Delete the minimal key.
525 deleteMin :: Map k a -> Map k a
526 deleteMin (Bin _ kx x Tip r) = r
527 deleteMin (Bin _ kx x l r) = balance kx x (deleteMin l) r
530 -- | /O(log n)/. Delete the maximal key.
531 deleteMax :: Map k a -> Map k a
532 deleteMax (Bin _ kx x l Tip) = l
533 deleteMax (Bin _ kx x l r) = balance kx x l (deleteMax r)
536 -- | /O(log n)/. Update the value at the minimal key.
537 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
539 = updateMinWithKey (\k x -> f x) m
541 -- | /O(log n)/. Update the value at the maximal key.
542 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
544 = updateMaxWithKey (\k x -> f x) m
547 -- | /O(log n)/. Update the value at the minimal key.
548 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
551 Bin sx kx x Tip r -> case f kx x of
553 Just x' -> Bin sx kx x' Tip r
554 Bin sx kx x l r -> balance kx x (updateMinWithKey f l) r
557 -- | /O(log n)/. Update the value at the maximal key.
558 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
561 Bin sx kx x l Tip -> case f kx x of
563 Just x' -> Bin sx kx x' l Tip
564 Bin sx kx x l r -> balance kx x l (updateMaxWithKey f r)
567 -- | /O(log n)/. Retrieves the minimal key of the map, and the map stripped from that element
568 -- @fail@s (in the monad) when passed an empty map.
569 minView :: Monad m => Map k a -> m (Map k a, (k,a))
570 minView Tip = fail "Map.minView: empty map"
571 minView x = return (swap $ deleteFindMin x)
573 -- | /O(log n)/. Retrieves the maximal key of the map, and the map stripped from that element
574 -- @fail@s (in the monad) when passed an empty map.
575 maxView :: Monad m => Map k a -> m (Map k a, (k,a))
576 maxView Tip = fail "Map.maxView: empty map"
577 maxView x = return (swap $ deleteFindMax x)
581 {--------------------------------------------------------------------
583 --------------------------------------------------------------------}
584 -- | The union of a list of maps:
585 -- (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
586 unions :: Ord k => [Map k a] -> Map k a
588 = foldlStrict union empty ts
590 -- | The union of a list of maps, with a combining operation:
591 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
592 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
594 = foldlStrict (unionWith f) empty ts
597 -- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
598 -- It prefers @t1@ when duplicate keys are encountered,
599 -- i.e. (@'union' == 'unionWith' 'const'@).
600 -- The implementation uses the efficient /hedge-union/ algorithm.
601 -- Hedge-union is more efficient on (bigset `union` smallset)
602 union :: Ord k => Map k a -> Map k a -> Map k a
605 union t1 t2 = hedgeUnionL (const LT) (const GT) t1 t2
607 -- left-biased hedge union
608 hedgeUnionL cmplo cmphi t1 Tip
610 hedgeUnionL cmplo cmphi Tip (Bin _ kx x l r)
611 = join kx x (filterGt cmplo l) (filterLt cmphi r)
612 hedgeUnionL cmplo cmphi (Bin _ kx x l r) t2
613 = join kx x (hedgeUnionL cmplo cmpkx l (trim cmplo cmpkx t2))
614 (hedgeUnionL cmpkx cmphi r (trim cmpkx cmphi t2))
616 cmpkx k = compare kx k
618 -- right-biased hedge union
619 hedgeUnionR cmplo cmphi t1 Tip
621 hedgeUnionR cmplo cmphi Tip (Bin _ kx x l r)
622 = join kx x (filterGt cmplo l) (filterLt cmphi r)
623 hedgeUnionR cmplo cmphi (Bin _ kx x l r) t2
624 = join kx newx (hedgeUnionR cmplo cmpkx l lt)
625 (hedgeUnionR cmpkx cmphi r gt)
627 cmpkx k = compare kx k
628 lt = trim cmplo cmpkx t2
629 (found,gt) = trimLookupLo kx cmphi t2
634 {--------------------------------------------------------------------
635 Union with a combining function
636 --------------------------------------------------------------------}
637 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
638 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
640 = unionWithKey (\k x y -> f x y) m1 m2
643 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
644 -- Hedge-union is more efficient on (bigset `union` smallset).
645 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
646 unionWithKey f Tip t2 = t2
647 unionWithKey f t1 Tip = t1
648 unionWithKey f t1 t2 = hedgeUnionWithKey f (const LT) (const GT) t1 t2
650 hedgeUnionWithKey f cmplo cmphi t1 Tip
652 hedgeUnionWithKey f cmplo cmphi Tip (Bin _ kx x l r)
653 = join kx x (filterGt cmplo l) (filterLt cmphi r)
654 hedgeUnionWithKey f cmplo cmphi (Bin _ kx x l r) t2
655 = join kx newx (hedgeUnionWithKey f cmplo cmpkx l lt)
656 (hedgeUnionWithKey f cmpkx cmphi r gt)
658 cmpkx k = compare kx k
659 lt = trim cmplo cmpkx t2
660 (found,gt) = trimLookupLo kx cmphi t2
663 Just (_,y) -> f kx x y
665 {--------------------------------------------------------------------
667 --------------------------------------------------------------------}
668 -- | /O(n+m)/. Difference of two maps.
669 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
670 difference :: Ord k => Map k a -> Map k b -> Map k a
671 difference Tip t2 = Tip
672 difference t1 Tip = t1
673 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
675 hedgeDiff cmplo cmphi Tip t
677 hedgeDiff cmplo cmphi (Bin _ kx x l r) Tip
678 = join kx x (filterGt cmplo l) (filterLt cmphi r)
679 hedgeDiff cmplo cmphi t (Bin _ kx x l r)
680 = merge (hedgeDiff cmplo cmpkx (trim cmplo cmpkx t) l)
681 (hedgeDiff cmpkx cmphi (trim cmpkx cmphi t) r)
683 cmpkx k = compare kx k
685 -- | /O(n+m)/. Difference with a combining function.
686 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
687 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
688 differenceWith f m1 m2
689 = differenceWithKey (\k x y -> f x y) m1 m2
691 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
692 -- encountered, the combining function is applied to the key and both values.
693 -- If it returns 'Nothing', the element is discarded (proper set difference). If
694 -- it returns (@'Just' y@), the element is updated with a new value @y@.
695 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
696 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
697 differenceWithKey f Tip t2 = Tip
698 differenceWithKey f t1 Tip = t1
699 differenceWithKey f t1 t2 = hedgeDiffWithKey f (const LT) (const GT) t1 t2
701 hedgeDiffWithKey f cmplo cmphi Tip t
703 hedgeDiffWithKey f cmplo cmphi (Bin _ kx x l r) Tip
704 = join kx x (filterGt cmplo l) (filterLt cmphi r)
705 hedgeDiffWithKey f cmplo cmphi t (Bin _ kx x l r)
707 Nothing -> merge tl tr
710 Nothing -> merge tl tr
711 Just z -> join ky z tl tr
713 cmpkx k = compare kx k
714 lt = trim cmplo cmpkx t
715 (found,gt) = trimLookupLo kx cmphi t
716 tl = hedgeDiffWithKey f cmplo cmpkx lt l
717 tr = hedgeDiffWithKey f cmpkx cmphi gt r
721 {--------------------------------------------------------------------
723 --------------------------------------------------------------------}
724 -- | /O(n+m)/. Intersection of two maps. The values in the first
725 -- map are returned, i.e. (@'intersection' m1 m2 == 'intersectionWith' 'const' m1 m2@).
726 intersection :: Ord k => Map k a -> Map k b -> Map k a
728 = intersectionWithKey (\k x y -> x) m1 m2
730 -- | /O(n+m)/. Intersection with a combining function.
731 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
732 intersectionWith f m1 m2
733 = intersectionWithKey (\k x y -> f x y) m1 m2
735 -- | /O(n+m)/. Intersection with a combining function.
736 -- Intersection is more efficient on (bigset `intersection` smallset)
737 --intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
738 --intersectionWithKey f Tip t = Tip
739 --intersectionWithKey f t Tip = Tip
740 --intersectionWithKey f t1 t2 = intersectWithKey f t1 t2
742 --intersectWithKey f Tip t = Tip
743 --intersectWithKey f t Tip = Tip
744 --intersectWithKey f t (Bin _ kx x l r)
746 -- Nothing -> merge tl tr
747 -- Just y -> join kx (f kx y x) tl tr
749 -- (lt,found,gt) = splitLookup kx t
750 -- tl = intersectWithKey f lt l
751 -- tr = intersectWithKey f gt r
754 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
755 intersectionWithKey f Tip t = Tip
756 intersectionWithKey f t Tip = Tip
757 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
759 let (lt,found,gt) = splitLookupWithKey k2 t1
760 tl = intersectionWithKey f lt l2
761 tr = intersectionWithKey f gt r2
763 Just (k,x) -> join k (f k x x2) tl tr
764 Nothing -> merge tl tr
765 else let (lt,found,gt) = splitLookup k1 t2
766 tl = intersectionWithKey f l1 lt
767 tr = intersectionWithKey f r1 gt
769 Just x -> join k1 (f k1 x1 x) tl tr
770 Nothing -> merge tl tr
774 {--------------------------------------------------------------------
776 --------------------------------------------------------------------}
778 -- This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
779 isSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
781 = isSubmapOfBy (==) m1 m2
784 The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if
785 all keys in @t1@ are in tree @t2@, and when @f@ returns 'True' when
786 applied to their respective values. For example, the following
787 expressions are all 'True':
789 > isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
790 > isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
791 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
793 But the following are all 'False':
795 > isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
796 > isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
797 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
799 isSubmapOfBy :: Ord k => (a->b->Bool) -> Map k a -> Map k b -> Bool
801 = (size t1 <= size t2) && (submap' f t1 t2)
803 submap' f Tip t = True
804 submap' f t Tip = False
805 submap' f (Bin _ kx x l r) t
808 Just y -> f x y && submap' f l lt && submap' f r gt
810 (lt,found,gt) = splitLookup kx t
812 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
813 -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
814 isProperSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
815 isProperSubmapOf m1 m2
816 = isProperSubmapOfBy (==) m1 m2
818 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
819 The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
820 @m1@ and @m2@ are not equal,
821 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
822 applied to their respective values. For example, the following
823 expressions are all 'True':
825 > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
826 > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
828 But the following are all 'False':
830 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
831 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
832 > isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
834 isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool
835 isProperSubmapOfBy f t1 t2
836 = (size t1 < size t2) && (submap' f t1 t2)
838 {--------------------------------------------------------------------
840 --------------------------------------------------------------------}
841 -- | /O(n)/. Filter all values that satisfy the predicate.
842 filter :: Ord k => (a -> Bool) -> Map k a -> Map k a
844 = filterWithKey (\k x -> p x) m
846 -- | /O(n)/. Filter all keys\/values that satisfy the predicate.
847 filterWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> Map k a
848 filterWithKey p Tip = Tip
849 filterWithKey p (Bin _ kx x l r)
850 | p kx x = join kx x (filterWithKey p l) (filterWithKey p r)
851 | otherwise = merge (filterWithKey p l) (filterWithKey p r)
854 -- | /O(n)/. partition the map according to a predicate. The first
855 -- map contains all elements that satisfy the predicate, the second all
856 -- elements that fail the predicate. See also 'split'.
857 partition :: Ord k => (a -> Bool) -> Map k a -> (Map k a,Map k a)
859 = partitionWithKey (\k x -> p x) m
861 -- | /O(n)/. partition the map according to a predicate. The first
862 -- map contains all elements that satisfy the predicate, the second all
863 -- elements that fail the predicate. See also 'split'.
864 partitionWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
865 partitionWithKey p Tip = (Tip,Tip)
866 partitionWithKey p (Bin _ kx x l r)
867 | p kx x = (join kx x l1 r1,merge l2 r2)
868 | otherwise = (merge l1 r1,join kx x l2 r2)
870 (l1,l2) = partitionWithKey p l
871 (r1,r2) = partitionWithKey p r
874 {--------------------------------------------------------------------
876 --------------------------------------------------------------------}
877 -- | /O(n)/. Map a function over all values in the map.
878 map :: (a -> b) -> Map k a -> Map k b
880 = mapWithKey (\k x -> f x) m
882 -- | /O(n)/. Map a function over all values in the map.
883 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
884 mapWithKey f Tip = Tip
885 mapWithKey f (Bin sx kx x l r)
886 = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
888 -- | /O(n)/. The function 'mapAccum' threads an accumulating
889 -- argument through the map in ascending order of keys.
890 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
892 = mapAccumWithKey (\a k x -> f a x) a m
894 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
895 -- argument through the map in ascending order of keys.
896 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
897 mapAccumWithKey f a t
900 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
901 -- argument throught the map in ascending order of keys.
902 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
907 -> let (a1,l') = mapAccumL f a l
909 (a3,r') = mapAccumL f a2 r
910 in (a3,Bin sx kx x' l' r')
912 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
913 -- argument throught the map in descending order of keys.
914 mapAccumR :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
919 -> let (a1,r') = mapAccumR f a r
921 (a3,l') = mapAccumR f a2 l
922 in (a3,Bin sx kx x' l' r')
925 -- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
927 -- The size of the result may be smaller if @f@ maps two or more distinct
928 -- keys to the same new key. In this case the value at the smallest of
929 -- these keys is retained.
931 mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
932 mapKeys = mapKeysWith (\x y->x)
935 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
937 -- The size of the result may be smaller if @f@ maps two or more distinct
938 -- keys to the same new key. In this case the associated values will be
939 -- combined using @c@.
941 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
942 mapKeysWith c f = fromListWith c . List.map fFirst . toList
943 where fFirst (x,y) = (f x, y)
947 -- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
948 -- is strictly monotonic.
949 -- /The precondition is not checked./
950 -- Semi-formally, we have:
952 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
953 -- > ==> mapKeysMonotonic f s == mapKeys f s
954 -- > where ls = keys s
956 mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
957 mapKeysMonotonic f Tip = Tip
958 mapKeysMonotonic f (Bin sz k x l r) =
959 Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
961 {--------------------------------------------------------------------
963 --------------------------------------------------------------------}
965 -- | /O(n)/. Fold the values in the map, such that
966 -- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
969 -- > elems map = fold (:) [] map
971 fold :: (a -> b -> b) -> b -> Map k a -> b
973 = foldWithKey (\k x z -> f x z) z m
975 -- | /O(n)/. Fold the keys and values in the map, such that
976 -- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
979 -- > keys map = foldWithKey (\k x ks -> k:ks) [] map
981 foldWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
985 -- | /O(n)/. In-order fold.
986 foldi :: (k -> a -> b -> b -> b) -> b -> Map k a -> b
988 foldi f z (Bin _ kx x l r) = f kx x (foldi f z l) (foldi f z r)
990 -- | /O(n)/. Post-order fold.
991 foldr :: (k -> a -> b -> b) -> b -> Map k a -> b
993 foldr f z (Bin _ kx x l r) = foldr f (f kx x (foldr f z r)) l
995 -- | /O(n)/. Pre-order fold.
996 foldl :: (b -> k -> a -> b) -> b -> Map k a -> b
998 foldl f z (Bin _ kx x l r) = foldl f (f (foldl f z l) kx x) r
1000 {--------------------------------------------------------------------
1002 --------------------------------------------------------------------}
1004 -- Return all elements of the map in the ascending order of their keys.
1005 elems :: Map k a -> [a]
1007 = [x | (k,x) <- assocs m]
1009 -- | /O(n)/. Return all keys of the map in ascending order.
1010 keys :: Map k a -> [k]
1012 = [k | (k,x) <- assocs m]
1014 -- | /O(n)/. The set of all keys of the map.
1015 keysSet :: Map k a -> Set.Set k
1016 keysSet m = Set.fromDistinctAscList (keys m)
1018 -- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
1019 assocs :: Map k a -> [(k,a)]
1023 {--------------------------------------------------------------------
1025 use [foldlStrict] to reduce demand on the control-stack
1026 --------------------------------------------------------------------}
1027 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
1028 fromList :: Ord k => [(k,a)] -> Map k a
1030 = foldlStrict ins empty xs
1032 ins t (k,x) = insert k x t
1034 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1035 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1037 = fromListWithKey (\k x y -> f x y) xs
1039 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1040 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1041 fromListWithKey f xs
1042 = foldlStrict ins empty xs
1044 ins t (k,x) = insertWithKey f k x t
1046 -- | /O(n)/. Convert to a list of key\/value pairs.
1047 toList :: Map k a -> [(k,a)]
1048 toList t = toAscList t
1050 -- | /O(n)/. Convert to an ascending list.
1051 toAscList :: Map k a -> [(k,a)]
1052 toAscList t = foldr (\k x xs -> (k,x):xs) [] t
1055 toDescList :: Map k a -> [(k,a)]
1056 toDescList t = foldl (\xs k x -> (k,x):xs) [] t
1059 {--------------------------------------------------------------------
1060 Building trees from ascending/descending lists can be done in linear time.
1062 Note that if [xs] is ascending that:
1063 fromAscList xs == fromList xs
1064 fromAscListWith f xs == fromListWith f xs
1065 --------------------------------------------------------------------}
1066 -- | /O(n)/. Build a map from an ascending list in linear time.
1067 -- /The precondition (input list is ascending) is not checked./
1068 fromAscList :: Eq k => [(k,a)] -> Map k a
1070 = fromAscListWithKey (\k x y -> x) xs
1072 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1073 -- /The precondition (input list is ascending) is not checked./
1074 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1075 fromAscListWith f xs
1076 = fromAscListWithKey (\k x y -> f x y) xs
1078 -- | /O(n)/. Build a map from an ascending list in linear time with a
1079 -- combining function for equal keys.
1080 -- /The precondition (input list is ascending) is not checked./
1081 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1082 fromAscListWithKey f xs
1083 = fromDistinctAscList (combineEq f xs)
1085 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1090 (x:xx) -> combineEq' x xx
1092 combineEq' z [] = [z]
1093 combineEq' z@(kz,zz) (x@(kx,xx):xs)
1094 | kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs
1095 | otherwise = z:combineEq' x xs
1098 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1099 -- /The precondition is not checked./
1100 fromDistinctAscList :: [(k,a)] -> Map k a
1101 fromDistinctAscList xs
1102 = build const (length xs) xs
1104 -- 1) use continutations so that we use heap space instead of stack space.
1105 -- 2) special case for n==5 to build bushier trees.
1106 build c 0 xs = c Tip xs
1107 build c 5 xs = case xs of
1108 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1109 -> c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3)) (singleton k5 x5)) xx
1110 build c n xs = seq nr $ build (buildR nr c) nl xs
1115 buildR n c l ((k,x):ys) = build (buildB l k x c) n ys
1116 buildB l k x c r zs = c (bin k x l r) zs
1120 {--------------------------------------------------------------------
1121 Utility functions that return sub-ranges of the original
1122 tree. Some functions take a comparison function as argument to
1123 allow comparisons against infinite values. A function [cmplo k]
1124 should be read as [compare lo k].
1126 [trim cmplo cmphi t] A tree that is either empty or where [cmplo k == LT]
1127 and [cmphi k == GT] for the key [k] of the root.
1128 [filterGt cmp t] A tree where for all keys [k]. [cmp k == LT]
1129 [filterLt cmp t] A tree where for all keys [k]. [cmp k == GT]
1131 [split k t] Returns two trees [l] and [r] where all keys
1132 in [l] are <[k] and all keys in [r] are >[k].
1133 [splitLookup k t] Just like [split] but also returns whether [k]
1134 was found in the tree.
1135 --------------------------------------------------------------------}
1137 {--------------------------------------------------------------------
1138 [trim lo hi t] trims away all subtrees that surely contain no
1139 values between the range [lo] to [hi]. The returned tree is either
1140 empty or the key of the root is between @lo@ and @hi@.
1141 --------------------------------------------------------------------}
1142 trim :: (k -> Ordering) -> (k -> Ordering) -> Map k a -> Map k a
1143 trim cmplo cmphi Tip = Tip
1144 trim cmplo cmphi t@(Bin sx kx x l r)
1146 LT -> case cmphi kx of
1148 le -> trim cmplo cmphi l
1149 ge -> trim cmplo cmphi r
1151 trimLookupLo :: Ord k => k -> (k -> Ordering) -> Map k a -> (Maybe (k,a), Map k a)
1152 trimLookupLo lo cmphi Tip = (Nothing,Tip)
1153 trimLookupLo lo cmphi t@(Bin sx kx x l r)
1154 = case compare lo kx of
1155 LT -> case cmphi kx of
1156 GT -> (lookupAssoc lo t, t)
1157 le -> trimLookupLo lo cmphi l
1158 GT -> trimLookupLo lo cmphi r
1159 EQ -> (Just (kx,x),trim (compare lo) cmphi r)
1162 {--------------------------------------------------------------------
1163 [filterGt k t] filter all keys >[k] from tree [t]
1164 [filterLt k t] filter all keys <[k] from tree [t]
1165 --------------------------------------------------------------------}
1166 filterGt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1167 filterGt cmp Tip = Tip
1168 filterGt cmp (Bin sx kx x l r)
1170 LT -> join kx x (filterGt cmp l) r
1171 GT -> filterGt cmp r
1174 filterLt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1175 filterLt cmp Tip = Tip
1176 filterLt cmp (Bin sx kx x l r)
1178 LT -> filterLt cmp l
1179 GT -> join kx x l (filterLt cmp r)
1182 {--------------------------------------------------------------------
1184 --------------------------------------------------------------------}
1185 -- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@ where
1186 -- 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@.
1187 split :: Ord k => k -> Map k a -> (Map k a,Map k a)
1188 split k Tip = (Tip,Tip)
1189 split k (Bin sx kx x l r)
1190 = case compare k kx of
1191 LT -> let (lt,gt) = split k l in (lt,join kx x gt r)
1192 GT -> let (lt,gt) = split k r in (join kx x l lt,gt)
1195 -- | /O(log n)/. The expression (@'splitLookup' k map@) splits a map just
1196 -- like 'split' but also returns @'lookup' k map@.
1197 splitLookup :: Ord k => k -> Map k a -> (Map k a,Maybe a,Map k a)
1198 splitLookup k Tip = (Tip,Nothing,Tip)
1199 splitLookup k (Bin sx kx x l r)
1200 = case compare k kx of
1201 LT -> let (lt,z,gt) = splitLookup k l in (lt,z,join kx x gt r)
1202 GT -> let (lt,z,gt) = splitLookup k r in (join kx x l lt,z,gt)
1206 splitLookupWithKey :: Ord k => k -> Map k a -> (Map k a,Maybe (k,a),Map k a)
1207 splitLookupWithKey k Tip = (Tip,Nothing,Tip)
1208 splitLookupWithKey k (Bin sx kx x l r)
1209 = case compare k kx of
1210 LT -> let (lt,z,gt) = splitLookupWithKey k l in (lt,z,join kx x gt r)
1211 GT -> let (lt,z,gt) = splitLookupWithKey k r in (join kx x l lt,z,gt)
1212 EQ -> (l,Just (kx, x),r)
1214 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
1215 -- element was found in the original set.
1216 splitMember :: Ord k => k -> Map k a -> (Map k a,Bool,Map k a)
1217 splitMember x t = let (l,m,r) = splitLookup x t in
1218 (l,maybe False (const True) m,r)
1221 {--------------------------------------------------------------------
1222 Utility functions that maintain the balance properties of the tree.
1223 All constructors assume that all values in [l] < [k] and all values
1224 in [r] > [k], and that [l] and [r] are valid trees.
1226 In order of sophistication:
1227 [Bin sz k x l r] The type constructor.
1228 [bin k x l r] Maintains the correct size, assumes that both [l]
1229 and [r] are balanced with respect to each other.
1230 [balance k x l r] Restores the balance and size.
1231 Assumes that the original tree was balanced and
1232 that [l] or [r] has changed by at most one element.
1233 [join k x l r] Restores balance and size.
1235 Furthermore, we can construct a new tree from two trees. Both operations
1236 assume that all values in [l] < all values in [r] and that [l] and [r]
1238 [glue l r] Glues [l] and [r] together. Assumes that [l] and
1239 [r] are already balanced with respect to each other.
1240 [merge l r] Merges two trees and restores balance.
1242 Note: in contrast to Adam's paper, we use (<=) comparisons instead
1243 of (<) comparisons in [join], [merge] and [balance].
1244 Quickcheck (on [difference]) showed that this was necessary in order
1245 to maintain the invariants. It is quite unsatisfactory that I haven't
1246 been able to find out why this is actually the case! Fortunately, it
1247 doesn't hurt to be a bit more conservative.
1248 --------------------------------------------------------------------}
1250 {--------------------------------------------------------------------
1252 --------------------------------------------------------------------}
1253 join :: Ord k => k -> a -> Map k a -> Map k a -> Map k a
1254 join kx x Tip r = insertMin kx x r
1255 join kx x l Tip = insertMax kx x l
1256 join kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
1257 | delta*sizeL <= sizeR = balance kz z (join kx x l lz) rz
1258 | delta*sizeR <= sizeL = balance ky y ly (join kx x ry r)
1259 | otherwise = bin kx x l r
1262 -- insertMin and insertMax don't perform potentially expensive comparisons.
1263 insertMax,insertMin :: k -> a -> Map k a -> Map k a
1266 Tip -> singleton kx x
1268 -> balance ky y l (insertMax kx x r)
1272 Tip -> singleton kx x
1274 -> balance ky y (insertMin kx x l) r
1276 {--------------------------------------------------------------------
1277 [merge l r]: merges two trees.
1278 --------------------------------------------------------------------}
1279 merge :: Map k a -> Map k a -> Map k a
1282 merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
1283 | delta*sizeL <= sizeR = balance ky y (merge l ly) ry
1284 | delta*sizeR <= sizeL = balance kx x lx (merge rx r)
1285 | otherwise = glue l r
1287 {--------------------------------------------------------------------
1288 [glue l r]: glues two trees together.
1289 Assumes that [l] and [r] are already balanced with respect to each other.
1290 --------------------------------------------------------------------}
1291 glue :: Map k a -> Map k a -> Map k a
1295 | size l > size r = let ((km,m),l') = deleteFindMax l in balance km m l' r
1296 | otherwise = let ((km,m),r') = deleteFindMin r in balance km m l r'
1299 -- | /O(log n)/. Delete and find the minimal element.
1300 deleteFindMin :: Map k a -> ((k,a),Map k a)
1303 Bin _ k x Tip r -> ((k,x),r)
1304 Bin _ k x l r -> let (km,l') = deleteFindMin l in (km,balance k x l' r)
1305 Tip -> (error "Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
1307 -- | /O(log n)/. Delete and find the maximal element.
1308 deleteFindMax :: Map k a -> ((k,a),Map k a)
1311 Bin _ k x l Tip -> ((k,x),l)
1312 Bin _ k x l r -> let (km,r') = deleteFindMax r in (km,balance k x l r')
1313 Tip -> (error "Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
1316 {--------------------------------------------------------------------
1317 [balance l x r] balances two trees with value x.
1318 The sizes of the trees should balance after decreasing the
1319 size of one of them. (a rotation).
1321 [delta] is the maximal relative difference between the sizes of
1322 two trees, it corresponds with the [w] in Adams' paper.
1323 [ratio] is the ratio between an outer and inner sibling of the
1324 heavier subtree in an unbalanced setting. It determines
1325 whether a double or single rotation should be performed
1326 to restore balance. It is correspondes with the inverse
1327 of $\alpha$ in Adam's article.
1330 - [delta] should be larger than 4.646 with a [ratio] of 2.
1331 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
1333 - A lower [delta] leads to a more 'perfectly' balanced tree.
1334 - A higher [delta] performs less rebalancing.
1336 - Balancing is automatic for random data and a balancing
1337 scheme is only necessary to avoid pathological worst cases.
1338 Almost any choice will do, and in practice, a rather large
1339 [delta] may perform better than smaller one.
1341 Note: in contrast to Adam's paper, we use a ratio of (at least) [2]
1342 to decide whether a single or double rotation is needed. Allthough
1343 he actually proves that this ratio is needed to maintain the
1344 invariants, his implementation uses an invalid ratio of [1].
1345 --------------------------------------------------------------------}
1350 balance :: k -> a -> Map k a -> Map k a -> Map k a
1352 | sizeL + sizeR <= 1 = Bin sizeX k x l r
1353 | sizeR >= delta*sizeL = rotateL k x l r
1354 | sizeL >= delta*sizeR = rotateR k x l r
1355 | otherwise = Bin sizeX k x l r
1359 sizeX = sizeL + sizeR + 1
1362 rotateL k x l r@(Bin _ _ _ ly ry)
1363 | size ly < ratio*size ry = singleL k x l r
1364 | otherwise = doubleL k x l r
1366 rotateR k x l@(Bin _ _ _ ly ry) r
1367 | size ry < ratio*size ly = singleR k x l r
1368 | otherwise = doubleR k x l r
1371 singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
1372 singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
1374 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)
1375 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)
1378 {--------------------------------------------------------------------
1379 The bin constructor maintains the size of the tree
1380 --------------------------------------------------------------------}
1381 bin :: k -> a -> Map k a -> Map k a -> Map k a
1383 = Bin (size l + size r + 1) k x l r
1386 {--------------------------------------------------------------------
1387 Eq converts the tree to a list. In a lazy setting, this
1388 actually seems one of the faster methods to compare two trees
1389 and it is certainly the simplest :-)
1390 --------------------------------------------------------------------}
1391 instance (Eq k,Eq a) => Eq (Map k a) where
1392 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
1394 {--------------------------------------------------------------------
1396 --------------------------------------------------------------------}
1398 instance (Ord k, Ord v) => Ord (Map k v) where
1399 compare m1 m2 = compare (toAscList m1) (toAscList m2)
1401 {--------------------------------------------------------------------
1403 --------------------------------------------------------------------}
1404 instance Functor (Map k) where
1407 instance Traversable (Map k) where
1408 traverse f Tip = pure Tip
1409 traverse f (Bin s k v l r)
1410 = flip (Bin s k) <$> traverse f l <*> f v <*> traverse f r
1412 instance Foldable (Map k) where
1413 foldMap _f Tip = mempty
1414 foldMap f (Bin _s _k v l r)
1415 = foldMap f l `mappend` f v `mappend` foldMap f r
1417 {--------------------------------------------------------------------
1419 --------------------------------------------------------------------}
1420 instance (Ord k, Read k, Read e) => Read (Map k e) where
1421 #ifdef __GLASGOW_HASKELL__
1422 readPrec = parens $ prec 10 $ do
1423 Ident "fromList" <- lexP
1425 return (fromList xs)
1427 readListPrec = readListPrecDefault
1429 readsPrec p = readParen (p > 10) $ \ r -> do
1430 ("fromList",s) <- lex r
1432 return (fromList xs,t)
1435 -- parses a pair of things with the syntax a:=b
1436 readPair :: (Read a, Read b) => ReadS (a,b)
1437 readPair s = do (a, ct1) <- reads s
1438 (":=", ct2) <- lex ct1
1439 (b, ct3) <- reads ct2
1442 {--------------------------------------------------------------------
1444 --------------------------------------------------------------------}
1445 instance (Show k, Show a) => Show (Map k a) where
1446 showsPrec d m = showParen (d > 10) $
1447 showString "fromList " . shows (toList m)
1449 showMap :: (Show k,Show a) => [(k,a)] -> ShowS
1453 = showChar '{' . showElem x . showTail xs
1455 showTail [] = showChar '}'
1456 showTail (x:xs) = showString ", " . showElem x . showTail xs
1458 showElem (k,x) = shows k . showString " := " . shows x
1461 -- | /O(n)/. Show the tree that implements the map. The tree is shown
1462 -- in a compressed, hanging format.
1463 showTree :: (Show k,Show a) => Map k a -> String
1465 = showTreeWith showElem True False m
1467 showElem k x = show k ++ ":=" ++ show x
1470 {- | /O(n)/. The expression (@'showTreeWith' showelem hang wide map@) shows
1471 the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
1472 'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
1473 @wide@ is 'True', an extra wide version is shown.
1475 > Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]]
1476 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t
1483 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t
1494 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t
1506 showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
1507 showTreeWith showelem hang wide t
1508 | hang = (showsTreeHang showelem wide [] t) ""
1509 | otherwise = (showsTree showelem wide [] [] t) ""
1511 showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
1512 showsTree showelem wide lbars rbars t
1514 Tip -> showsBars lbars . showString "|\n"
1516 -> showsBars lbars . showString (showelem kx x) . showString "\n"
1518 -> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
1519 showWide wide rbars .
1520 showsBars lbars . showString (showelem kx x) . showString "\n" .
1521 showWide wide lbars .
1522 showsTree showelem wide (withEmpty lbars) (withBar lbars) l
1524 showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
1525 showsTreeHang showelem wide bars t
1527 Tip -> showsBars bars . showString "|\n"
1529 -> showsBars bars . showString (showelem kx x) . showString "\n"
1531 -> showsBars bars . showString (showelem kx x) . showString "\n" .
1532 showWide wide bars .
1533 showsTreeHang showelem wide (withBar bars) l .
1534 showWide wide bars .
1535 showsTreeHang showelem wide (withEmpty bars) r
1539 | wide = showString (concat (reverse bars)) . showString "|\n"
1542 showsBars :: [String] -> ShowS
1546 _ -> showString (concat (reverse (tail bars))) . showString node
1549 withBar bars = "| ":bars
1550 withEmpty bars = " ":bars
1552 {--------------------------------------------------------------------
1554 --------------------------------------------------------------------}
1556 #include "Typeable.h"
1557 INSTANCE_TYPEABLE2(Map,mapTc,"Map")
1559 {--------------------------------------------------------------------
1561 --------------------------------------------------------------------}
1562 -- | /O(n)/. Test if the internal map structure is valid.
1563 valid :: Ord k => Map k a -> Bool
1565 = balanced t && ordered t && validsize t
1568 = bounded (const True) (const True) t
1573 Bin sz kx x l r -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
1575 -- | Exported only for "Debug.QuickCheck"
1576 balanced :: Map k a -> Bool
1580 Bin sz kx x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1581 balanced l && balanced r
1585 = (realsize t == Just (size t))
1590 Bin sz kx x l r -> case (realsize l,realsize r) of
1591 (Just n,Just m) | n+m+1 == sz -> Just sz
1594 {--------------------------------------------------------------------
1596 --------------------------------------------------------------------}
1600 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
1604 {--------------------------------------------------------------------
1606 --------------------------------------------------------------------}
1607 testTree xs = fromList [(x,"*") | x <- xs]
1608 test1 = testTree [1..20]
1609 test2 = testTree [30,29..10]
1610 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1612 {--------------------------------------------------------------------
1614 --------------------------------------------------------------------}
1619 { configMaxTest = 500
1620 , configMaxFail = 5000
1621 , configSize = \n -> (div n 2 + 3)
1622 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1626 {--------------------------------------------------------------------
1627 Arbitrary, reasonably balanced trees
1628 --------------------------------------------------------------------}
1629 instance (Enum k,Arbitrary a) => Arbitrary (Map k a) where
1630 arbitrary = sized (arbtree 0 maxkey)
1631 where maxkey = 10000
1633 arbtree :: (Enum k,Arbitrary a) => Int -> Int -> Int -> Gen (Map k a)
1635 | n <= 0 = return Tip
1636 | lo >= hi = return Tip
1637 | otherwise = do{ x <- arbitrary
1638 ; i <- choose (lo,hi)
1639 ; m <- choose (1,30)
1640 ; let (ml,mr) | m==(1::Int)= (1,2)
1644 ; l <- arbtree lo (i-1) (n `div` ml)
1645 ; r <- arbtree (i+1) hi (n `div` mr)
1646 ; return (bin (toEnum i) x l r)
1650 {--------------------------------------------------------------------
1652 --------------------------------------------------------------------}
1653 forValid :: (Show k,Enum k,Show a,Arbitrary a,Testable b) => (Map k a -> b) -> Property
1655 = forAll arbitrary $ \t ->
1656 -- classify (balanced t) "balanced" $
1657 classify (size t == 0) "empty" $
1658 classify (size t > 0 && size t <= 10) "small" $
1659 classify (size t > 10 && size t <= 64) "medium" $
1660 classify (size t > 64) "large" $
1663 forValidIntTree :: Testable a => (Map Int Int -> a) -> Property
1667 forValidUnitTree :: Testable a => (Map Int () -> a) -> Property
1673 = forValidUnitTree $ \t -> valid t
1675 {--------------------------------------------------------------------
1676 Single, Insert, Delete
1677 --------------------------------------------------------------------}
1678 prop_Single :: Int -> Int -> Bool
1680 = (insert k x empty == singleton k x)
1682 prop_InsertValid :: Int -> Property
1684 = forValidUnitTree $ \t -> valid (insert k () t)
1686 prop_InsertDelete :: Int -> Map Int () -> Property
1687 prop_InsertDelete k t
1688 = (lookup k t == Nothing) ==> delete k (insert k () t) == t
1690 prop_DeleteValid :: Int -> Property
1692 = forValidUnitTree $ \t ->
1693 valid (delete k (insert k () t))
1695 {--------------------------------------------------------------------
1697 --------------------------------------------------------------------}
1698 prop_Join :: Int -> Property
1700 = forValidUnitTree $ \t ->
1701 let (l,r) = split k t
1702 in valid (join k () l r)
1704 prop_Merge :: Int -> Property
1706 = forValidUnitTree $ \t ->
1707 let (l,r) = split k t
1708 in valid (merge l r)
1711 {--------------------------------------------------------------------
1713 --------------------------------------------------------------------}
1714 prop_UnionValid :: Property
1716 = forValidUnitTree $ \t1 ->
1717 forValidUnitTree $ \t2 ->
1720 prop_UnionInsert :: Int -> Int -> Map Int Int -> Bool
1721 prop_UnionInsert k x t
1722 = union (singleton k x) t == insert k x t
1724 prop_UnionAssoc :: Map Int Int -> Map Int Int -> Map Int Int -> Bool
1725 prop_UnionAssoc t1 t2 t3
1726 = union t1 (union t2 t3) == union (union t1 t2) t3
1728 prop_UnionComm :: Map Int Int -> Map Int Int -> Bool
1729 prop_UnionComm t1 t2
1730 = (union t1 t2 == unionWith (\x y -> y) t2 t1)
1733 = forValidIntTree $ \t1 ->
1734 forValidIntTree $ \t2 ->
1735 valid (unionWithKey (\k x y -> x+y) t1 t2)
1737 prop_UnionWith :: [(Int,Int)] -> [(Int,Int)] -> Bool
1738 prop_UnionWith xs ys
1739 = sum (elems (unionWith (+) (fromListWith (+) xs) (fromListWith (+) ys)))
1740 == (sum (Prelude.map snd xs) + sum (Prelude.map snd ys))
1743 = forValidUnitTree $ \t1 ->
1744 forValidUnitTree $ \t2 ->
1745 valid (difference t1 t2)
1747 prop_Diff :: [(Int,Int)] -> [(Int,Int)] -> Bool
1749 = List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys)))
1750 == List.sort ((List.\\) (nub (Prelude.map fst xs)) (nub (Prelude.map fst ys)))
1753 = forValidUnitTree $ \t1 ->
1754 forValidUnitTree $ \t2 ->
1755 valid (intersection t1 t2)
1757 prop_Int :: [(Int,Int)] -> [(Int,Int)] -> Bool
1759 = List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys)))
1760 == List.sort (nub ((List.intersect) (Prelude.map fst xs) (Prelude.map fst ys)))
1762 {--------------------------------------------------------------------
1764 --------------------------------------------------------------------}
1766 = forAll (choose (5,100)) $ \n ->
1767 let xs = [(x,()) | x <- [0..n::Int]]
1768 in fromAscList xs == fromList xs
1770 prop_List :: [Int] -> Bool
1772 = (sort (nub xs) == [x | (x,()) <- toList (fromList [(x,()) | x <- xs])])