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
117 , fromDistinctAscList
129 , isSubmapOf, isSubmapOfBy
130 , isProperSubmapOf, isProperSubmapOfBy
157 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
158 import qualified Data.Set as Set
159 import qualified Data.List as List
160 import Data.Monoid (Monoid(..))
162 import Control.Applicative (Applicative(..))
163 import Data.Traversable (Traversable(traverse))
164 import Data.Foldable (Foldable(foldMap))
168 import qualified Prelude
169 import qualified List
170 import Debug.QuickCheck
171 import List(nub,sort)
174 #if __GLASGOW_HASKELL__
176 import Data.Generics.Basics
177 import Data.Generics.Instances
180 {--------------------------------------------------------------------
182 --------------------------------------------------------------------}
185 -- | /O(log n)/. Find the value at a key.
186 -- Calls 'error' when the element can not be found.
187 (!) :: Ord k => Map k a -> k -> a
190 -- | /O(n+m)/. See 'difference'.
191 (\\) :: Ord k => Map k a -> Map k b -> Map k a
192 m1 \\ m2 = difference m1 m2
194 {--------------------------------------------------------------------
196 --------------------------------------------------------------------}
197 -- | A Map from keys @k@ to values @a@.
199 | Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
203 instance (Ord k) => Monoid (Map k v) where
208 #if __GLASGOW_HASKELL__
210 {--------------------------------------------------------------------
212 --------------------------------------------------------------------}
214 -- This instance preserves data abstraction at the cost of inefficiency.
215 -- We omit reflection services for the sake of data abstraction.
217 instance (Data k, Data a, Ord k) => Data (Map k a) where
218 gfoldl f z map = z fromList `f` (toList map)
219 toConstr _ = error "toConstr"
220 gunfold _ _ = error "gunfold"
221 dataTypeOf _ = mkNorepType "Data.Map.Map"
222 dataCast2 f = gcast2 f
226 {--------------------------------------------------------------------
228 --------------------------------------------------------------------}
229 -- | /O(1)/. Is the map empty?
230 null :: Map k a -> Bool
234 Bin sz k x l r -> False
236 -- | /O(1)/. The number of elements in the map.
237 size :: Map k a -> Int
244 -- | /O(log n)/. Lookup the value at a key in the map.
245 lookup :: (Monad m,Ord k) => k -> Map k a -> m a
246 lookup k t = case lookup' k t of
248 Nothing -> fail "Data.Map.lookup: Key not found"
249 lookup' :: Ord k => k -> Map k a -> Maybe a
254 -> case compare k kx of
259 lookupAssoc :: Ord k => k -> Map k a -> Maybe (k,a)
264 -> case compare k kx of
265 LT -> lookupAssoc k l
266 GT -> lookupAssoc k r
269 -- | /O(log n)/. Is the key a member of the map?
270 member :: Ord k => k -> Map k a -> Bool
276 -- | /O(log n)/. Is the key not a member of the map?
277 notMember :: Ord k => k -> Map k a -> Bool
278 notMember k m = not $ member k m
280 -- | /O(log n)/. Find the value at a key.
281 -- Calls 'error' when the element can not be found.
282 find :: Ord k => k -> Map k a -> a
285 Nothing -> error "Map.find: element not in the map"
288 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
289 -- the value at key @k@ or returns @def@ when the key is not in the map.
290 findWithDefault :: Ord k => a -> k -> Map k a -> a
291 findWithDefault def k m
298 {--------------------------------------------------------------------
300 --------------------------------------------------------------------}
301 -- | /O(1)/. The empty map.
306 -- | /O(1)/. A map with a single element.
307 singleton :: k -> a -> Map k a
311 {--------------------------------------------------------------------
313 --------------------------------------------------------------------}
314 -- | /O(log n)/. Insert a new key and value in the map.
315 -- If the key is already present in the map, the associated value is
316 -- replaced with the supplied value, i.e. 'insert' is equivalent to
317 -- @'insertWith' 'const'@.
318 insert :: Ord k => k -> a -> Map k a -> Map k a
321 Tip -> singleton kx x
323 -> case compare kx ky of
324 LT -> balance ky y (insert kx x l) r
325 GT -> balance ky y l (insert kx x r)
326 EQ -> Bin sz kx x l r
328 -- | /O(log n)/. Insert with a combining function.
329 -- @'insertWith' f key value mp@
330 -- will insert the pair (key, value) into @mp@ if key does
331 -- not exist in the map. If the key does exist, the function will
332 -- insert the pair @(key, f new_value old_value)@.
333 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
335 = insertWithKey (\k x y -> f x y) k x m
337 -- | /O(log n)/. Insert with a combining function.
338 -- @'insertWithKey' f key value mp@
339 -- will insert the pair (key, value) into @mp@ if key does
340 -- not exist in the map. If the key does exist, the function will
341 -- insert the pair @(key,f key new_value old_value)@.
342 -- Note that the key passed to f is the same key passed to 'insertWithKey'.
343 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
344 insertWithKey f kx x t
346 Tip -> singleton kx x
348 -> case compare kx ky of
349 LT -> balance ky y (insertWithKey f kx x l) r
350 GT -> balance ky y l (insertWithKey f kx x r)
351 EQ -> Bin sy kx (f kx x y) l r
353 -- | /O(log n)/. The expression (@'insertLookupWithKey' f k x map@)
354 -- is a pair where the first element is equal to (@'lookup' k map@)
355 -- and the second element equal to (@'insertWithKey' f k x map@).
356 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a,Map k a)
357 insertLookupWithKey f kx x t
359 Tip -> (Nothing, singleton kx x)
361 -> case compare kx ky of
362 LT -> let (found,l') = insertLookupWithKey f kx x l in (found,balance ky y l' r)
363 GT -> let (found,r') = insertLookupWithKey f kx x r in (found,balance ky y l r')
364 EQ -> (Just y, Bin sy kx (f kx x y) l r)
366 {--------------------------------------------------------------------
368 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
369 --------------------------------------------------------------------}
370 -- | /O(log n)/. Delete a key and its value from the map. When the key is not
371 -- a member of the map, the original map is returned.
372 delete :: Ord k => k -> Map k a -> Map k a
377 -> case compare k kx of
378 LT -> balance kx x (delete k l) r
379 GT -> balance kx x l (delete k r)
382 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
383 -- a member of the map, the original map is returned.
384 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
386 = adjustWithKey (\k x -> f x) k m
388 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
389 -- a member of the map, the original map is returned.
390 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
392 = updateWithKey (\k x -> Just (f k x)) k m
394 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
395 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
396 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
397 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
399 = updateWithKey (\k x -> f x) k m
401 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
402 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
403 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
404 -- to the new value @y@.
405 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
410 -> case compare k kx of
411 LT -> balance kx x (updateWithKey f k l) r
412 GT -> balance kx x l (updateWithKey f k r)
414 Just x' -> Bin sx kx x' l r
417 -- | /O(log n)/. Lookup and update.
418 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
419 updateLookupWithKey f k t
423 -> case compare k kx of
424 LT -> let (found,l') = updateLookupWithKey f k l in (found,balance kx x l' r)
425 GT -> let (found,r') = updateLookupWithKey f k r in (found,balance kx x l r')
427 Just x' -> (Just x',Bin sx kx x' l r)
428 Nothing -> (Just x,glue l r)
430 {--------------------------------------------------------------------
432 --------------------------------------------------------------------}
433 -- | /O(log n)/. Return the /index/ of a key. The index is a number from
434 -- /0/ up to, but not including, the 'size' of the map. Calls 'error' when
435 -- the key is not a 'member' of the map.
436 findIndex :: Ord k => k -> Map k a -> Int
438 = case lookupIndex k t of
439 Nothing -> error "Map.findIndex: element is not in the map"
442 -- | /O(log n)/. Lookup the /index/ of a key. The index is a number from
443 -- /0/ up to, but not including, the 'size' of the map.
444 lookupIndex :: (Monad m,Ord k) => k -> Map k a -> m Int
445 lookupIndex k t = case lookup 0 t of
446 Nothing -> fail "Data.Map.lookupIndex: Key not found."
449 lookup idx Tip = Nothing
450 lookup idx (Bin _ kx x l r)
451 = case compare k kx of
453 GT -> lookup (idx + size l + 1) r
454 EQ -> Just (idx + size l)
456 -- | /O(log n)/. Retrieve an element by /index/. Calls 'error' when an
457 -- invalid index is used.
458 elemAt :: Int -> Map k a -> (k,a)
459 elemAt i Tip = error "Map.elemAt: index out of range"
460 elemAt i (Bin _ kx x l r)
461 = case compare i sizeL of
463 GT -> elemAt (i-sizeL-1) r
468 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
469 -- invalid index is used.
470 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
471 updateAt f i Tip = error "Map.updateAt: index out of range"
472 updateAt f i (Bin sx kx x l r)
473 = case compare i sizeL of
475 GT -> updateAt f (i-sizeL-1) r
477 Just x' -> Bin sx kx x' l r
482 -- | /O(log n)/. Delete the element at /index/.
483 -- Defined as (@'deleteAt' i map = 'updateAt' (\k x -> 'Nothing') i map@).
484 deleteAt :: Int -> Map k a -> Map k a
486 = updateAt (\k x -> Nothing) i map
489 {--------------------------------------------------------------------
491 --------------------------------------------------------------------}
492 -- | /O(log n)/. The minimal key of the map.
493 findMin :: Map k a -> (k,a)
494 findMin (Bin _ kx x Tip r) = (kx,x)
495 findMin (Bin _ kx x l r) = findMin l
496 findMin Tip = error "Map.findMin: empty tree has no minimal element"
498 -- | /O(log n)/. The maximal key of the map.
499 findMax :: Map k a -> (k,a)
500 findMax (Bin _ kx x l Tip) = (kx,x)
501 findMax (Bin _ kx x l r) = findMax r
502 findMax Tip = error "Map.findMax: empty tree has no maximal element"
504 -- | /O(log n)/. Delete the minimal key.
505 deleteMin :: Map k a -> Map k a
506 deleteMin (Bin _ kx x Tip r) = r
507 deleteMin (Bin _ kx x l r) = balance kx x (deleteMin l) r
510 -- | /O(log n)/. Delete the maximal key.
511 deleteMax :: Map k a -> Map k a
512 deleteMax (Bin _ kx x l Tip) = l
513 deleteMax (Bin _ kx x l r) = balance kx x l (deleteMax r)
516 -- | /O(log n)/. Update the value at the minimal key.
517 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
519 = updateMinWithKey (\k x -> f x) m
521 -- | /O(log n)/. Update the value at the maximal key.
522 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
524 = updateMaxWithKey (\k x -> f x) m
527 -- | /O(log n)/. Update the value at the minimal key.
528 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
531 Bin sx kx x Tip r -> case f kx x of
533 Just x' -> Bin sx kx x' Tip r
534 Bin sx kx x l r -> balance kx x (updateMinWithKey f l) r
537 -- | /O(log n)/. Update the value at the maximal key.
538 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
541 Bin sx kx x l Tip -> case f kx x of
543 Just x' -> Bin sx kx x' l Tip
544 Bin sx kx x l r -> balance kx x l (updateMaxWithKey f r)
548 {--------------------------------------------------------------------
550 --------------------------------------------------------------------}
551 -- | The union of a list of maps:
552 -- (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
553 unions :: Ord k => [Map k a] -> Map k a
555 = foldlStrict union empty ts
557 -- | The union of a list of maps, with a combining operation:
558 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
559 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
561 = foldlStrict (unionWith f) empty ts
564 -- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
565 -- It prefers @t1@ when duplicate keys are encountered,
566 -- i.e. (@'union' == 'unionWith' 'const'@).
567 -- The implementation uses the efficient /hedge-union/ algorithm.
568 -- Hedge-union is more efficient on (bigset `union` smallset)
569 union :: Ord k => Map k a -> Map k a -> Map k a
572 union t1 t2 = hedgeUnionL (const LT) (const GT) t1 t2
574 -- left-biased hedge union
575 hedgeUnionL cmplo cmphi t1 Tip
577 hedgeUnionL cmplo cmphi Tip (Bin _ kx x l r)
578 = join kx x (filterGt cmplo l) (filterLt cmphi r)
579 hedgeUnionL cmplo cmphi (Bin _ kx x l r) t2
580 = join kx x (hedgeUnionL cmplo cmpkx l (trim cmplo cmpkx t2))
581 (hedgeUnionL cmpkx cmphi r (trim cmpkx cmphi t2))
583 cmpkx k = compare kx k
585 -- right-biased hedge union
586 hedgeUnionR cmplo cmphi t1 Tip
588 hedgeUnionR cmplo cmphi Tip (Bin _ kx x l r)
589 = join kx x (filterGt cmplo l) (filterLt cmphi r)
590 hedgeUnionR cmplo cmphi (Bin _ kx x l r) t2
591 = join kx newx (hedgeUnionR cmplo cmpkx l lt)
592 (hedgeUnionR cmpkx cmphi r gt)
594 cmpkx k = compare kx k
595 lt = trim cmplo cmpkx t2
596 (found,gt) = trimLookupLo kx cmphi t2
601 {--------------------------------------------------------------------
602 Union with a combining function
603 --------------------------------------------------------------------}
604 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
605 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
607 = unionWithKey (\k x y -> f x y) m1 m2
610 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
611 -- Hedge-union is more efficient on (bigset `union` smallset).
612 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
613 unionWithKey f Tip t2 = t2
614 unionWithKey f t1 Tip = t1
615 unionWithKey f t1 t2 = hedgeUnionWithKey f (const LT) (const GT) t1 t2
617 hedgeUnionWithKey f cmplo cmphi t1 Tip
619 hedgeUnionWithKey f cmplo cmphi Tip (Bin _ kx x l r)
620 = join kx x (filterGt cmplo l) (filterLt cmphi r)
621 hedgeUnionWithKey f cmplo cmphi (Bin _ kx x l r) t2
622 = join kx newx (hedgeUnionWithKey f cmplo cmpkx l lt)
623 (hedgeUnionWithKey f cmpkx cmphi r gt)
625 cmpkx k = compare kx k
626 lt = trim cmplo cmpkx t2
627 (found,gt) = trimLookupLo kx cmphi t2
630 Just (_,y) -> f kx x y
632 {--------------------------------------------------------------------
634 --------------------------------------------------------------------}
635 -- | /O(n+m)/. Difference of two maps.
636 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
637 difference :: Ord k => Map k a -> Map k b -> Map k a
638 difference Tip t2 = Tip
639 difference t1 Tip = t1
640 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
642 hedgeDiff cmplo cmphi Tip t
644 hedgeDiff cmplo cmphi (Bin _ kx x l r) Tip
645 = join kx x (filterGt cmplo l) (filterLt cmphi r)
646 hedgeDiff cmplo cmphi t (Bin _ kx x l r)
647 = merge (hedgeDiff cmplo cmpkx (trim cmplo cmpkx t) l)
648 (hedgeDiff cmpkx cmphi (trim cmpkx cmphi t) r)
650 cmpkx k = compare kx k
652 -- | /O(n+m)/. Difference with a combining function.
653 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
654 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
655 differenceWith f m1 m2
656 = differenceWithKey (\k x y -> f x y) m1 m2
658 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
659 -- encountered, the combining function is applied to the key and both values.
660 -- If it returns 'Nothing', the element is discarded (proper set difference). If
661 -- it returns (@'Just' y@), the element is updated with a new value @y@.
662 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
663 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
664 differenceWithKey f Tip t2 = Tip
665 differenceWithKey f t1 Tip = t1
666 differenceWithKey f t1 t2 = hedgeDiffWithKey f (const LT) (const GT) t1 t2
668 hedgeDiffWithKey f cmplo cmphi Tip t
670 hedgeDiffWithKey f cmplo cmphi (Bin _ kx x l r) Tip
671 = join kx x (filterGt cmplo l) (filterLt cmphi r)
672 hedgeDiffWithKey f cmplo cmphi t (Bin _ kx x l r)
674 Nothing -> merge tl tr
677 Nothing -> merge tl tr
678 Just z -> join ky z tl tr
680 cmpkx k = compare kx k
681 lt = trim cmplo cmpkx t
682 (found,gt) = trimLookupLo kx cmphi t
683 tl = hedgeDiffWithKey f cmplo cmpkx lt l
684 tr = hedgeDiffWithKey f cmpkx cmphi gt r
688 {--------------------------------------------------------------------
690 --------------------------------------------------------------------}
691 -- | /O(n+m)/. Intersection of two maps. The values in the first
692 -- map are returned, i.e. (@'intersection' m1 m2 == 'intersectionWith' 'const' m1 m2@).
693 intersection :: Ord k => Map k a -> Map k b -> Map k a
695 = intersectionWithKey (\k x y -> x) m1 m2
697 -- | /O(n+m)/. Intersection with a combining function.
698 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
699 intersectionWith f m1 m2
700 = intersectionWithKey (\k x y -> f x y) m1 m2
702 -- | /O(n+m)/. Intersection with a combining function.
703 -- Intersection is more efficient on (bigset `intersection` smallset)
704 --intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
705 --intersectionWithKey f Tip t = Tip
706 --intersectionWithKey f t Tip = Tip
707 --intersectionWithKey f t1 t2 = intersectWithKey f t1 t2
709 --intersectWithKey f Tip t = Tip
710 --intersectWithKey f t Tip = Tip
711 --intersectWithKey f t (Bin _ kx x l r)
713 -- Nothing -> merge tl tr
714 -- Just y -> join kx (f kx y x) tl tr
716 -- (lt,found,gt) = splitLookup kx t
717 -- tl = intersectWithKey f lt l
718 -- tr = intersectWithKey f gt r
721 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
722 intersectionWithKey f Tip t = Tip
723 intersectionWithKey f t Tip = Tip
724 intersectionWithKey f t1@(Bin s1 k1 x1 l1 r1) t2@(Bin s2 k2 x2 l2 r2) =
726 let (lt,found,gt) = splitLookupWithKey k2 t1
727 tl = intersectionWithKey f lt l2
728 tr = intersectionWithKey f gt r2
730 Just (k,x) -> join k (f k x x2) tl tr
731 Nothing -> merge tl tr
732 else let (lt,found,gt) = splitLookup k1 t2
733 tl = intersectionWithKey f l1 lt
734 tr = intersectionWithKey f r1 gt
736 Just x -> join k1 (f k1 x1 x) tl tr
737 Nothing -> merge tl tr
741 {--------------------------------------------------------------------
743 --------------------------------------------------------------------}
745 -- This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
746 isSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
748 = isSubmapOfBy (==) m1 m2
751 The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if
752 all keys in @t1@ are in tree @t2@, and when @f@ returns 'True' when
753 applied to their respective values. For example, the following
754 expressions are all 'True':
756 > isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
757 > isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
758 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
760 But the following are all 'False':
762 > isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
763 > isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
764 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
766 isSubmapOfBy :: Ord k => (a->b->Bool) -> Map k a -> Map k b -> Bool
768 = (size t1 <= size t2) && (submap' f t1 t2)
770 submap' f Tip t = True
771 submap' f t Tip = False
772 submap' f (Bin _ kx x l r) t
775 Just y -> f x y && submap' f l lt && submap' f r gt
777 (lt,found,gt) = splitLookup kx t
779 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
780 -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
781 isProperSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
782 isProperSubmapOf m1 m2
783 = isProperSubmapOfBy (==) m1 m2
785 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
786 The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
787 @m1@ and @m2@ are not equal,
788 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
789 applied to their respective values. For example, the following
790 expressions are all 'True':
792 > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
793 > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
795 But the following are all 'False':
797 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
798 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
799 > isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
801 isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool
802 isProperSubmapOfBy f t1 t2
803 = (size t1 < size t2) && (submap' f t1 t2)
805 {--------------------------------------------------------------------
807 --------------------------------------------------------------------}
808 -- | /O(n)/. Filter all values that satisfy the predicate.
809 filter :: Ord k => (a -> Bool) -> Map k a -> Map k a
811 = filterWithKey (\k x -> p x) m
813 -- | /O(n)/. Filter all keys\/values that satisfy the predicate.
814 filterWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> Map k a
815 filterWithKey p Tip = Tip
816 filterWithKey p (Bin _ kx x l r)
817 | p kx x = join kx x (filterWithKey p l) (filterWithKey p r)
818 | otherwise = merge (filterWithKey p l) (filterWithKey p r)
821 -- | /O(n)/. partition the map according to a predicate. The first
822 -- map contains all elements that satisfy the predicate, the second all
823 -- elements that fail the predicate. See also 'split'.
824 partition :: Ord k => (a -> Bool) -> Map k a -> (Map k a,Map k a)
826 = partitionWithKey (\k x -> p x) m
828 -- | /O(n)/. partition the map according to a predicate. The first
829 -- map contains all elements that satisfy the predicate, the second all
830 -- elements that fail the predicate. See also 'split'.
831 partitionWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
832 partitionWithKey p Tip = (Tip,Tip)
833 partitionWithKey p (Bin _ kx x l r)
834 | p kx x = (join kx x l1 r1,merge l2 r2)
835 | otherwise = (merge l1 r1,join kx x l2 r2)
837 (l1,l2) = partitionWithKey p l
838 (r1,r2) = partitionWithKey p r
841 {--------------------------------------------------------------------
843 --------------------------------------------------------------------}
844 -- | /O(n)/. Map a function over all values in the map.
845 map :: (a -> b) -> Map k a -> Map k b
847 = mapWithKey (\k x -> f x) m
849 -- | /O(n)/. Map a function over all values in the map.
850 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
851 mapWithKey f Tip = Tip
852 mapWithKey f (Bin sx kx x l r)
853 = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
855 -- | /O(n)/. The function 'mapAccum' threads an accumulating
856 -- argument through the map in ascending order of keys.
857 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
859 = mapAccumWithKey (\a k x -> f a x) a m
861 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
862 -- argument through the map in ascending order of keys.
863 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
864 mapAccumWithKey f a t
867 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
868 -- argument throught the map in ascending order of keys.
869 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
874 -> let (a1,l') = mapAccumL f a l
876 (a3,r') = mapAccumL f a2 r
877 in (a3,Bin sx kx x' l' r')
879 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
880 -- argument throught the map in descending order of keys.
881 mapAccumR :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
886 -> let (a1,r') = mapAccumR f a r
888 (a3,l') = mapAccumR f a2 l
889 in (a3,Bin sx kx x' l' r')
892 -- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
894 -- The size of the result may be smaller if @f@ maps two or more distinct
895 -- keys to the same new key. In this case the value at the smallest of
896 -- these keys is retained.
898 mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
899 mapKeys = mapKeysWith (\x y->x)
902 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
904 -- The size of the result may be smaller if @f@ maps two or more distinct
905 -- keys to the same new key. In this case the associated values will be
906 -- combined using @c@.
908 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
909 mapKeysWith c f = fromListWith c . List.map fFirst . toList
910 where fFirst (x,y) = (f x, y)
914 -- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
915 -- is strictly monotonic.
916 -- /The precondition is not checked./
917 -- Semi-formally, we have:
919 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
920 -- > ==> mapKeysMonotonic f s == mapKeys f s
921 -- > where ls = keys s
923 mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
924 mapKeysMonotonic f Tip = Tip
925 mapKeysMonotonic f (Bin sz k x l r) =
926 Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
928 {--------------------------------------------------------------------
930 --------------------------------------------------------------------}
932 -- | /O(n)/. Fold the values in the map, such that
933 -- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
936 -- > elems map = fold (:) [] map
938 fold :: (a -> b -> b) -> b -> Map k a -> b
940 = foldWithKey (\k x z -> f x z) z m
942 -- | /O(n)/. Fold the keys and values in the map, such that
943 -- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
946 -- > keys map = foldWithKey (\k x ks -> k:ks) [] map
948 foldWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
952 -- | /O(n)/. In-order fold.
953 foldi :: (k -> a -> b -> b -> b) -> b -> Map k a -> b
955 foldi f z (Bin _ kx x l r) = f kx x (foldi f z l) (foldi f z r)
957 -- | /O(n)/. Post-order fold.
958 foldr :: (k -> a -> b -> b) -> b -> Map k a -> b
960 foldr f z (Bin _ kx x l r) = foldr f (f kx x (foldr f z r)) l
962 -- | /O(n)/. Pre-order fold.
963 foldl :: (b -> k -> a -> b) -> b -> Map k a -> b
965 foldl f z (Bin _ kx x l r) = foldl f (f (foldl f z l) kx x) r
967 {--------------------------------------------------------------------
969 --------------------------------------------------------------------}
971 -- Return all elements of the map in the ascending order of their keys.
972 elems :: Map k a -> [a]
974 = [x | (k,x) <- assocs m]
976 -- | /O(n)/. Return all keys of the map in ascending order.
977 keys :: Map k a -> [k]
979 = [k | (k,x) <- assocs m]
981 -- | /O(n)/. The set of all keys of the map.
982 keysSet :: Map k a -> Set.Set k
983 keysSet m = Set.fromDistinctAscList (keys m)
985 -- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
986 assocs :: Map k a -> [(k,a)]
990 {--------------------------------------------------------------------
992 use [foldlStrict] to reduce demand on the control-stack
993 --------------------------------------------------------------------}
994 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
995 fromList :: Ord k => [(k,a)] -> Map k a
997 = foldlStrict ins empty xs
999 ins t (k,x) = insert k x t
1001 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
1002 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
1004 = fromListWithKey (\k x y -> f x y) xs
1006 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
1007 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1008 fromListWithKey f xs
1009 = foldlStrict ins empty xs
1011 ins t (k,x) = insertWithKey f k x t
1013 -- | /O(n)/. Convert to a list of key\/value pairs.
1014 toList :: Map k a -> [(k,a)]
1015 toList t = toAscList t
1017 -- | /O(n)/. Convert to an ascending list.
1018 toAscList :: Map k a -> [(k,a)]
1019 toAscList t = foldr (\k x xs -> (k,x):xs) [] t
1022 toDescList :: Map k a -> [(k,a)]
1023 toDescList t = foldl (\xs k x -> (k,x):xs) [] t
1026 {--------------------------------------------------------------------
1027 Building trees from ascending/descending lists can be done in linear time.
1029 Note that if [xs] is ascending that:
1030 fromAscList xs == fromList xs
1031 fromAscListWith f xs == fromListWith f xs
1032 --------------------------------------------------------------------}
1033 -- | /O(n)/. Build a map from an ascending list in linear time.
1034 -- /The precondition (input list is ascending) is not checked./
1035 fromAscList :: Eq k => [(k,a)] -> Map k a
1037 = fromAscListWithKey (\k x y -> x) xs
1039 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1040 -- /The precondition (input list is ascending) is not checked./
1041 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1042 fromAscListWith f xs
1043 = fromAscListWithKey (\k x y -> f x y) xs
1045 -- | /O(n)/. Build a map from an ascending list in linear time with a
1046 -- combining function for equal keys.
1047 -- /The precondition (input list is ascending) is not checked./
1048 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1049 fromAscListWithKey f xs
1050 = fromDistinctAscList (combineEq f xs)
1052 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1057 (x:xx) -> combineEq' x xx
1059 combineEq' z [] = [z]
1060 combineEq' z@(kz,zz) (x@(kx,xx):xs)
1061 | kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs
1062 | otherwise = z:combineEq' x xs
1065 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1066 -- /The precondition is not checked./
1067 fromDistinctAscList :: [(k,a)] -> Map k a
1068 fromDistinctAscList xs
1069 = build const (length xs) xs
1071 -- 1) use continutations so that we use heap space instead of stack space.
1072 -- 2) special case for n==5 to build bushier trees.
1073 build c 0 xs = c Tip xs
1074 build c 5 xs = case xs of
1075 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1076 -> c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3)) (singleton k5 x5)) xx
1077 build c n xs = seq nr $ build (buildR nr c) nl xs
1082 buildR n c l ((k,x):ys) = build (buildB l k x c) n ys
1083 buildB l k x c r zs = c (bin k x l r) zs
1087 {--------------------------------------------------------------------
1088 Utility functions that return sub-ranges of the original
1089 tree. Some functions take a comparison function as argument to
1090 allow comparisons against infinite values. A function [cmplo k]
1091 should be read as [compare lo k].
1093 [trim cmplo cmphi t] A tree that is either empty or where [cmplo k == LT]
1094 and [cmphi k == GT] for the key [k] of the root.
1095 [filterGt cmp t] A tree where for all keys [k]. [cmp k == LT]
1096 [filterLt cmp t] A tree where for all keys [k]. [cmp k == GT]
1098 [split k t] Returns two trees [l] and [r] where all keys
1099 in [l] are <[k] and all keys in [r] are >[k].
1100 [splitLookup k t] Just like [split] but also returns whether [k]
1101 was found in the tree.
1102 --------------------------------------------------------------------}
1104 {--------------------------------------------------------------------
1105 [trim lo hi t] trims away all subtrees that surely contain no
1106 values between the range [lo] to [hi]. The returned tree is either
1107 empty or the key of the root is between @lo@ and @hi@.
1108 --------------------------------------------------------------------}
1109 trim :: (k -> Ordering) -> (k -> Ordering) -> Map k a -> Map k a
1110 trim cmplo cmphi Tip = Tip
1111 trim cmplo cmphi t@(Bin sx kx x l r)
1113 LT -> case cmphi kx of
1115 le -> trim cmplo cmphi l
1116 ge -> trim cmplo cmphi r
1118 trimLookupLo :: Ord k => k -> (k -> Ordering) -> Map k a -> (Maybe (k,a), Map k a)
1119 trimLookupLo lo cmphi Tip = (Nothing,Tip)
1120 trimLookupLo lo cmphi t@(Bin sx kx x l r)
1121 = case compare lo kx of
1122 LT -> case cmphi kx of
1123 GT -> (lookupAssoc lo t, t)
1124 le -> trimLookupLo lo cmphi l
1125 GT -> trimLookupLo lo cmphi r
1126 EQ -> (Just (kx,x),trim (compare lo) cmphi r)
1129 {--------------------------------------------------------------------
1130 [filterGt k t] filter all keys >[k] from tree [t]
1131 [filterLt k t] filter all keys <[k] from tree [t]
1132 --------------------------------------------------------------------}
1133 filterGt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1134 filterGt cmp Tip = Tip
1135 filterGt cmp (Bin sx kx x l r)
1137 LT -> join kx x (filterGt cmp l) r
1138 GT -> filterGt cmp r
1141 filterLt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1142 filterLt cmp Tip = Tip
1143 filterLt cmp (Bin sx kx x l r)
1145 LT -> filterLt cmp l
1146 GT -> join kx x l (filterLt cmp r)
1149 {--------------------------------------------------------------------
1151 --------------------------------------------------------------------}
1152 -- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@ where
1153 -- 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@.
1154 split :: Ord k => k -> Map k a -> (Map k a,Map k a)
1155 split k Tip = (Tip,Tip)
1156 split k (Bin sx kx x l r)
1157 = case compare k kx of
1158 LT -> let (lt,gt) = split k l in (lt,join kx x gt r)
1159 GT -> let (lt,gt) = split k r in (join kx x l lt,gt)
1162 -- | /O(log n)/. The expression (@'splitLookup' k map@) splits a map just
1163 -- like 'split' but also returns @'lookup' k map@.
1164 splitLookup :: Ord k => k -> Map k a -> (Map k a,Maybe a,Map k a)
1165 splitLookup k Tip = (Tip,Nothing,Tip)
1166 splitLookup k (Bin sx kx x l r)
1167 = case compare k kx of
1168 LT -> let (lt,z,gt) = splitLookup k l in (lt,z,join kx x gt r)
1169 GT -> let (lt,z,gt) = splitLookup k r in (join kx x l lt,z,gt)
1173 splitLookupWithKey :: Ord k => k -> Map k a -> (Map k a,Maybe (k,a),Map k a)
1174 splitLookupWithKey k Tip = (Tip,Nothing,Tip)
1175 splitLookupWithKey k (Bin sx kx x l r)
1176 = case compare k kx of
1177 LT -> let (lt,z,gt) = splitLookupWithKey k l in (lt,z,join kx x gt r)
1178 GT -> let (lt,z,gt) = splitLookupWithKey k r in (join kx x l lt,z,gt)
1179 EQ -> (l,Just (kx, x),r)
1181 -- | /O(log n)/. Performs a 'split' but also returns whether the pivot
1182 -- element was found in the original set.
1183 splitMember :: Ord k => k -> Map k a -> (Map k a,Bool,Map k a)
1184 splitMember x t = let (l,m,r) = splitLookup x t in
1185 (l,maybe False (const True) m,r)
1188 {--------------------------------------------------------------------
1189 Utility functions that maintain the balance properties of the tree.
1190 All constructors assume that all values in [l] < [k] and all values
1191 in [r] > [k], and that [l] and [r] are valid trees.
1193 In order of sophistication:
1194 [Bin sz k x l r] The type constructor.
1195 [bin k x l r] Maintains the correct size, assumes that both [l]
1196 and [r] are balanced with respect to each other.
1197 [balance k x l r] Restores the balance and size.
1198 Assumes that the original tree was balanced and
1199 that [l] or [r] has changed by at most one element.
1200 [join k x l r] Restores balance and size.
1202 Furthermore, we can construct a new tree from two trees. Both operations
1203 assume that all values in [l] < all values in [r] and that [l] and [r]
1205 [glue l r] Glues [l] and [r] together. Assumes that [l] and
1206 [r] are already balanced with respect to each other.
1207 [merge l r] Merges two trees and restores balance.
1209 Note: in contrast to Adam's paper, we use (<=) comparisons instead
1210 of (<) comparisons in [join], [merge] and [balance].
1211 Quickcheck (on [difference]) showed that this was necessary in order
1212 to maintain the invariants. It is quite unsatisfactory that I haven't
1213 been able to find out why this is actually the case! Fortunately, it
1214 doesn't hurt to be a bit more conservative.
1215 --------------------------------------------------------------------}
1217 {--------------------------------------------------------------------
1219 --------------------------------------------------------------------}
1220 join :: Ord k => k -> a -> Map k a -> Map k a -> Map k a
1221 join kx x Tip r = insertMin kx x r
1222 join kx x l Tip = insertMax kx x l
1223 join kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
1224 | delta*sizeL <= sizeR = balance kz z (join kx x l lz) rz
1225 | delta*sizeR <= sizeL = balance ky y ly (join kx x ry r)
1226 | otherwise = bin kx x l r
1229 -- insertMin and insertMax don't perform potentially expensive comparisons.
1230 insertMax,insertMin :: k -> a -> Map k a -> Map k a
1233 Tip -> singleton kx x
1235 -> balance ky y l (insertMax kx x r)
1239 Tip -> singleton kx x
1241 -> balance ky y (insertMin kx x l) r
1243 {--------------------------------------------------------------------
1244 [merge l r]: merges two trees.
1245 --------------------------------------------------------------------}
1246 merge :: Map k a -> Map k a -> Map k a
1249 merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
1250 | delta*sizeL <= sizeR = balance ky y (merge l ly) ry
1251 | delta*sizeR <= sizeL = balance kx x lx (merge rx r)
1252 | otherwise = glue l r
1254 {--------------------------------------------------------------------
1255 [glue l r]: glues two trees together.
1256 Assumes that [l] and [r] are already balanced with respect to each other.
1257 --------------------------------------------------------------------}
1258 glue :: Map k a -> Map k a -> Map k a
1262 | size l > size r = let ((km,m),l') = deleteFindMax l in balance km m l' r
1263 | otherwise = let ((km,m),r') = deleteFindMin r in balance km m l r'
1266 -- | /O(log n)/. Delete and find the minimal element.
1267 deleteFindMin :: Map k a -> ((k,a),Map k a)
1270 Bin _ k x Tip r -> ((k,x),r)
1271 Bin _ k x l r -> let (km,l') = deleteFindMin l in (km,balance k x l' r)
1272 Tip -> (error "Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
1274 -- | /O(log n)/. Delete and find the maximal element.
1275 deleteFindMax :: Map k a -> ((k,a),Map k a)
1278 Bin _ k x l Tip -> ((k,x),l)
1279 Bin _ k x l r -> let (km,r') = deleteFindMax r in (km,balance k x l r')
1280 Tip -> (error "Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
1283 {--------------------------------------------------------------------
1284 [balance l x r] balances two trees with value x.
1285 The sizes of the trees should balance after decreasing the
1286 size of one of them. (a rotation).
1288 [delta] is the maximal relative difference between the sizes of
1289 two trees, it corresponds with the [w] in Adams' paper.
1290 [ratio] is the ratio between an outer and inner sibling of the
1291 heavier subtree in an unbalanced setting. It determines
1292 whether a double or single rotation should be performed
1293 to restore balance. It is correspondes with the inverse
1294 of $\alpha$ in Adam's article.
1297 - [delta] should be larger than 4.646 with a [ratio] of 2.
1298 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
1300 - A lower [delta] leads to a more 'perfectly' balanced tree.
1301 - A higher [delta] performs less rebalancing.
1303 - Balancing is automatic for random data and a balancing
1304 scheme is only necessary to avoid pathological worst cases.
1305 Almost any choice will do, and in practice, a rather large
1306 [delta] may perform better than smaller one.
1308 Note: in contrast to Adam's paper, we use a ratio of (at least) [2]
1309 to decide whether a single or double rotation is needed. Allthough
1310 he actually proves that this ratio is needed to maintain the
1311 invariants, his implementation uses an invalid ratio of [1].
1312 --------------------------------------------------------------------}
1317 balance :: k -> a -> Map k a -> Map k a -> Map k a
1319 | sizeL + sizeR <= 1 = Bin sizeX k x l r
1320 | sizeR >= delta*sizeL = rotateL k x l r
1321 | sizeL >= delta*sizeR = rotateR k x l r
1322 | otherwise = Bin sizeX k x l r
1326 sizeX = sizeL + sizeR + 1
1329 rotateL k x l r@(Bin _ _ _ ly ry)
1330 | size ly < ratio*size ry = singleL k x l r
1331 | otherwise = doubleL k x l r
1333 rotateR k x l@(Bin _ _ _ ly ry) r
1334 | size ry < ratio*size ly = singleR k x l r
1335 | otherwise = doubleR k x l r
1338 singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
1339 singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
1341 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)
1342 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)
1345 {--------------------------------------------------------------------
1346 The bin constructor maintains the size of the tree
1347 --------------------------------------------------------------------}
1348 bin :: k -> a -> Map k a -> Map k a -> Map k a
1350 = Bin (size l + size r + 1) k x l r
1353 {--------------------------------------------------------------------
1354 Eq converts the tree to a list. In a lazy setting, this
1355 actually seems one of the faster methods to compare two trees
1356 and it is certainly the simplest :-)
1357 --------------------------------------------------------------------}
1358 instance (Eq k,Eq a) => Eq (Map k a) where
1359 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
1361 {--------------------------------------------------------------------
1363 --------------------------------------------------------------------}
1365 instance (Ord k, Ord v) => Ord (Map k v) where
1366 compare m1 m2 = compare (toAscList m1) (toAscList m2)
1368 {--------------------------------------------------------------------
1370 --------------------------------------------------------------------}
1371 instance Functor (Map k) where
1374 instance Traversable (Map k) where
1375 traverse f Tip = pure Tip
1376 traverse f (Bin s k v l r)
1377 = flip (Bin s k) <$> traverse f l <*> f v <*> traverse f r
1379 instance Foldable (Map k) where
1380 foldMap _f Tip = mempty
1381 foldMap f (Bin _s _k v l r)
1382 = foldMap f l `mappend` f v `mappend` foldMap f r
1384 {--------------------------------------------------------------------
1386 --------------------------------------------------------------------}
1387 instance (Ord k, Read k, Read e) => Read (Map k e) where
1388 #ifdef __GLASGOW_HASKELL__
1389 readPrec = parens $ prec 10 $ do
1390 Ident "fromList" <- lexP
1392 return (fromList xs)
1394 readListPrec = readListPrecDefault
1396 readsPrec p = readParen (p > 10) $ \ r -> do
1397 ("fromList",s) <- lex r
1399 return (fromList xs,t)
1402 -- parses a pair of things with the syntax a:=b
1403 readPair :: (Read a, Read b) => ReadS (a,b)
1404 readPair s = do (a, ct1) <- reads s
1405 (":=", ct2) <- lex ct1
1406 (b, ct3) <- reads ct2
1409 {--------------------------------------------------------------------
1411 --------------------------------------------------------------------}
1412 instance (Show k, Show a) => Show (Map k a) where
1413 showsPrec d m = showParen (d > 10) $
1414 showString "fromList " . shows (toList m)
1416 showMap :: (Show k,Show a) => [(k,a)] -> ShowS
1420 = showChar '{' . showElem x . showTail xs
1422 showTail [] = showChar '}'
1423 showTail (x:xs) = showString ", " . showElem x . showTail xs
1425 showElem (k,x) = shows k . showString " := " . shows x
1428 -- | /O(n)/. Show the tree that implements the map. The tree is shown
1429 -- in a compressed, hanging format.
1430 showTree :: (Show k,Show a) => Map k a -> String
1432 = showTreeWith showElem True False m
1434 showElem k x = show k ++ ":=" ++ show x
1437 {- | /O(n)/. The expression (@'showTreeWith' showelem hang wide map@) shows
1438 the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
1439 'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
1440 @wide@ is 'True', an extra wide version is shown.
1442 > Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]]
1443 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t
1450 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t
1461 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t
1473 showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
1474 showTreeWith showelem hang wide t
1475 | hang = (showsTreeHang showelem wide [] t) ""
1476 | otherwise = (showsTree showelem wide [] [] t) ""
1478 showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
1479 showsTree showelem wide lbars rbars t
1481 Tip -> showsBars lbars . showString "|\n"
1483 -> showsBars lbars . showString (showelem kx x) . showString "\n"
1485 -> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
1486 showWide wide rbars .
1487 showsBars lbars . showString (showelem kx x) . showString "\n" .
1488 showWide wide lbars .
1489 showsTree showelem wide (withEmpty lbars) (withBar lbars) l
1491 showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
1492 showsTreeHang showelem wide bars t
1494 Tip -> showsBars bars . showString "|\n"
1496 -> showsBars bars . showString (showelem kx x) . showString "\n"
1498 -> showsBars bars . showString (showelem kx x) . showString "\n" .
1499 showWide wide bars .
1500 showsTreeHang showelem wide (withBar bars) l .
1501 showWide wide bars .
1502 showsTreeHang showelem wide (withEmpty bars) r
1506 | wide = showString (concat (reverse bars)) . showString "|\n"
1509 showsBars :: [String] -> ShowS
1513 _ -> showString (concat (reverse (tail bars))) . showString node
1516 withBar bars = "| ":bars
1517 withEmpty bars = " ":bars
1519 {--------------------------------------------------------------------
1521 --------------------------------------------------------------------}
1523 #include "Typeable.h"
1524 INSTANCE_TYPEABLE2(Map,mapTc,"Map")
1526 {--------------------------------------------------------------------
1528 --------------------------------------------------------------------}
1529 -- | /O(n)/. Test if the internal map structure is valid.
1530 valid :: Ord k => Map k a -> Bool
1532 = balanced t && ordered t && validsize t
1535 = bounded (const True) (const True) t
1540 Bin sz kx x l r -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
1542 -- | Exported only for "Debug.QuickCheck"
1543 balanced :: Map k a -> Bool
1547 Bin sz kx x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1548 balanced l && balanced r
1552 = (realsize t == Just (size t))
1557 Bin sz kx x l r -> case (realsize l,realsize r) of
1558 (Just n,Just m) | n+m+1 == sz -> Just sz
1561 {--------------------------------------------------------------------
1563 --------------------------------------------------------------------}
1567 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
1571 {--------------------------------------------------------------------
1573 --------------------------------------------------------------------}
1574 testTree xs = fromList [(x,"*") | x <- xs]
1575 test1 = testTree [1..20]
1576 test2 = testTree [30,29..10]
1577 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1579 {--------------------------------------------------------------------
1581 --------------------------------------------------------------------}
1586 { configMaxTest = 500
1587 , configMaxFail = 5000
1588 , configSize = \n -> (div n 2 + 3)
1589 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1593 {--------------------------------------------------------------------
1594 Arbitrary, reasonably balanced trees
1595 --------------------------------------------------------------------}
1596 instance (Enum k,Arbitrary a) => Arbitrary (Map k a) where
1597 arbitrary = sized (arbtree 0 maxkey)
1598 where maxkey = 10000
1600 arbtree :: (Enum k,Arbitrary a) => Int -> Int -> Int -> Gen (Map k a)
1602 | n <= 0 = return Tip
1603 | lo >= hi = return Tip
1604 | otherwise = do{ x <- arbitrary
1605 ; i <- choose (lo,hi)
1606 ; m <- choose (1,30)
1607 ; let (ml,mr) | m==(1::Int)= (1,2)
1611 ; l <- arbtree lo (i-1) (n `div` ml)
1612 ; r <- arbtree (i+1) hi (n `div` mr)
1613 ; return (bin (toEnum i) x l r)
1617 {--------------------------------------------------------------------
1619 --------------------------------------------------------------------}
1620 forValid :: (Show k,Enum k,Show a,Arbitrary a,Testable b) => (Map k a -> b) -> Property
1622 = forAll arbitrary $ \t ->
1623 -- classify (balanced t) "balanced" $
1624 classify (size t == 0) "empty" $
1625 classify (size t > 0 && size t <= 10) "small" $
1626 classify (size t > 10 && size t <= 64) "medium" $
1627 classify (size t > 64) "large" $
1630 forValidIntTree :: Testable a => (Map Int Int -> a) -> Property
1634 forValidUnitTree :: Testable a => (Map Int () -> a) -> Property
1640 = forValidUnitTree $ \t -> valid t
1642 {--------------------------------------------------------------------
1643 Single, Insert, Delete
1644 --------------------------------------------------------------------}
1645 prop_Single :: Int -> Int -> Bool
1647 = (insert k x empty == singleton k x)
1649 prop_InsertValid :: Int -> Property
1651 = forValidUnitTree $ \t -> valid (insert k () t)
1653 prop_InsertDelete :: Int -> Map Int () -> Property
1654 prop_InsertDelete k t
1655 = (lookup k t == Nothing) ==> delete k (insert k () t) == t
1657 prop_DeleteValid :: Int -> Property
1659 = forValidUnitTree $ \t ->
1660 valid (delete k (insert k () t))
1662 {--------------------------------------------------------------------
1664 --------------------------------------------------------------------}
1665 prop_Join :: Int -> Property
1667 = forValidUnitTree $ \t ->
1668 let (l,r) = split k t
1669 in valid (join k () l r)
1671 prop_Merge :: Int -> Property
1673 = forValidUnitTree $ \t ->
1674 let (l,r) = split k t
1675 in valid (merge l r)
1678 {--------------------------------------------------------------------
1680 --------------------------------------------------------------------}
1681 prop_UnionValid :: Property
1683 = forValidUnitTree $ \t1 ->
1684 forValidUnitTree $ \t2 ->
1687 prop_UnionInsert :: Int -> Int -> Map Int Int -> Bool
1688 prop_UnionInsert k x t
1689 = union (singleton k x) t == insert k x t
1691 prop_UnionAssoc :: Map Int Int -> Map Int Int -> Map Int Int -> Bool
1692 prop_UnionAssoc t1 t2 t3
1693 = union t1 (union t2 t3) == union (union t1 t2) t3
1695 prop_UnionComm :: Map Int Int -> Map Int Int -> Bool
1696 prop_UnionComm t1 t2
1697 = (union t1 t2 == unionWith (\x y -> y) t2 t1)
1700 = forValidIntTree $ \t1 ->
1701 forValidIntTree $ \t2 ->
1702 valid (unionWithKey (\k x y -> x+y) t1 t2)
1704 prop_UnionWith :: [(Int,Int)] -> [(Int,Int)] -> Bool
1705 prop_UnionWith xs ys
1706 = sum (elems (unionWith (+) (fromListWith (+) xs) (fromListWith (+) ys)))
1707 == (sum (Prelude.map snd xs) + sum (Prelude.map snd ys))
1710 = forValidUnitTree $ \t1 ->
1711 forValidUnitTree $ \t2 ->
1712 valid (difference t1 t2)
1714 prop_Diff :: [(Int,Int)] -> [(Int,Int)] -> Bool
1716 = List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys)))
1717 == List.sort ((List.\\) (nub (Prelude.map fst xs)) (nub (Prelude.map fst ys)))
1720 = forValidUnitTree $ \t1 ->
1721 forValidUnitTree $ \t2 ->
1722 valid (intersection t1 t2)
1724 prop_Int :: [(Int,Int)] -> [(Int,Int)] -> Bool
1726 = List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys)))
1727 == List.sort (nub ((List.intersect) (Prelude.map fst xs) (Prelude.map fst ys)))
1729 {--------------------------------------------------------------------
1731 --------------------------------------------------------------------}
1733 = forAll (choose (5,100)) $ \n ->
1734 let xs = [(x,()) | x <- [0..n::Int]]
1735 in fromAscList xs == fromList xs
1737 prop_List :: [Int] -> Bool
1739 = (sort (nub xs) == [x | (x,()) <- toList (fromList [(x,()) | x <- xs])])