1 -----------------------------------------------------------------------------
4 -- Copyright : (c) Daan Leijen 2002
6 -- Maintainer : libraries@haskell.org
7 -- Stability : provisional
8 -- Portability : portable
10 -- An efficient implementation of maps from keys to values (dictionaries).
12 -- This module is intended to be imported @qualified@, to avoid name
13 -- clashes with Prelude functions. eg.
15 -- > import Data.Map as Map
17 -- The implementation of 'Map' is based on /size balanced/ binary trees (or
18 -- trees of /bounded balance/) as described by:
20 -- * Stephen Adams, \"/Efficient sets: a balancing act/\",
21 -- Journal of Functional Programming 3(4):553-562, October 1993,
22 -- <http://www.swiss.ai.mit.edu/~adams/BB>.
24 -- * J. Nievergelt and E.M. Reingold,
25 -- \"/Binary search trees of bounded balance/\",
26 -- SIAM journal of computing 2(1), March 1973.
27 -----------------------------------------------------------------------------
31 Map -- instance Eq,Show,Read
50 , insertWith, insertWithKey, insertLookupWithKey
110 , fromDistinctAscList
122 , isSubmapOf, isSubmapOfBy
123 , isProperSubmapOf, isProperSubmapOfBy
150 import Prelude hiding (lookup,map,filter,foldr,foldl,null)
151 import qualified Data.Set as Set
152 import qualified Data.List as List
153 import Data.Monoid (Monoid(..))
155 import Control.Applicative (Applicative(..))
156 import Data.Traversable (Traversable(traverse))
157 import Data.Foldable (Foldable(foldMap))
161 import qualified Prelude
162 import qualified List
163 import Debug.QuickCheck
164 import List(nub,sort)
167 #if __GLASGOW_HASKELL__
169 import Data.Generics.Basics
170 import Data.Generics.Instances
173 {--------------------------------------------------------------------
175 --------------------------------------------------------------------}
178 -- | /O(log n)/. Find the value at a key.
179 -- Calls 'error' when the element can not be found.
180 (!) :: Ord k => Map k a -> k -> a
183 -- | /O(n+m)/. See 'difference'.
184 (\\) :: Ord k => Map k a -> Map k b -> Map k a
185 m1 \\ m2 = difference m1 m2
187 {--------------------------------------------------------------------
189 --------------------------------------------------------------------}
190 -- | A Map from keys @k@ to values @a@.
192 | Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
196 instance (Ord k) => Monoid (Map k v) where
201 #if __GLASGOW_HASKELL__
203 {--------------------------------------------------------------------
205 --------------------------------------------------------------------}
207 -- This instance preserves data abstraction at the cost of inefficiency.
208 -- We omit reflection services for the sake of data abstraction.
210 instance (Data k, Data a, Ord k) => Data (Map k a) where
211 gfoldl f z map = z fromList `f` (toList map)
212 toConstr _ = error "toConstr"
213 gunfold _ _ = error "gunfold"
214 dataTypeOf _ = mkNorepType "Data.Map.Map"
219 {--------------------------------------------------------------------
221 --------------------------------------------------------------------}
222 -- | /O(1)/. Is the map empty?
223 null :: Map k a -> Bool
227 Bin sz k x l r -> False
229 -- | /O(1)/. The number of elements in the map.
230 size :: Map k a -> Int
237 -- | /O(log n)/. Lookup the value at a key in the map.
238 lookup :: (Monad m,Ord k) => k -> Map k a -> m a
239 lookup k t = case lookup' k t of
241 Nothing -> fail "Data.Map.lookup: Key not found"
242 lookup' :: Ord k => k -> Map k a -> Maybe a
247 -> case compare k kx of
252 -- | /O(log n)/. Is the key a member of the map?
253 member :: Ord k => k -> Map k a -> Bool
259 -- | /O(log n)/. Find the value at a key.
260 -- Calls 'error' when the element can not be found.
261 find :: Ord k => k -> Map k a -> a
264 Nothing -> error "Map.find: element not in the map"
267 -- | /O(log n)/. The expression @('findWithDefault' def k map)@ returns
268 -- the value at key @k@ or returns @def@ when the key is not in the map.
269 findWithDefault :: Ord k => a -> k -> Map k a -> a
270 findWithDefault def k m
277 {--------------------------------------------------------------------
279 --------------------------------------------------------------------}
280 -- | /O(1)/. The empty map.
285 -- | /O(1)/. A map with a single element.
286 singleton :: k -> a -> Map k a
290 {--------------------------------------------------------------------
292 --------------------------------------------------------------------}
293 -- | /O(log n)/. Insert a new key and value in the map.
294 -- If the key is already present in the map, the associated value is
295 -- replaced with the supplied value, i.e. 'insert' is equivalent to
296 -- @'insertWith' 'const'@.
297 insert :: Ord k => k -> a -> Map k a -> Map k a
300 Tip -> singleton kx x
302 -> case compare kx ky of
303 LT -> balance ky y (insert kx x l) r
304 GT -> balance ky y l (insert kx x r)
305 EQ -> Bin sz kx x l r
307 -- | /O(log n)/. Insert with a combining function.
308 -- @'insertWith' f key value mp@
309 -- will insert the pair (key, value) into @mp@ if key does
310 -- not exist in the map. If the key does exist, the function will
311 -- insert @f new_value old_value@.
312 insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
314 = insertWithKey (\k x y -> f x y) k x m
316 -- | /O(log n)/. Insert with a combining function.
317 -- @'insertWithKey' f key value mp@
318 -- will insert the pair (key, value) into @mp@ if key does
319 -- not exist in the map. If the key does exist, the function will
320 -- insert @f key new_value old_value@.
321 insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
322 insertWithKey f kx x t
324 Tip -> singleton kx x
326 -> case compare kx ky of
327 LT -> balance ky y (insertWithKey f kx x l) r
328 GT -> balance ky y l (insertWithKey f kx x r)
329 EQ -> Bin sy ky (f ky x y) l r
331 -- | /O(log n)/. The expression (@'insertLookupWithKey' f k x map@)
332 -- is a pair where the first element is equal to (@'lookup' k map@)
333 -- and the second element equal to (@'insertWithKey' f k x map@).
334 insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a,Map k a)
335 insertLookupWithKey f kx x t
337 Tip -> (Nothing, singleton kx x)
339 -> case compare kx ky of
340 LT -> let (found,l') = insertLookupWithKey f kx x l in (found,balance ky y l' r)
341 GT -> let (found,r') = insertLookupWithKey f kx x r in (found,balance ky y l r')
342 EQ -> (Just y, Bin sy ky (f ky x y) l r)
344 {--------------------------------------------------------------------
346 [delete] is the inlined version of [deleteWith (\k x -> Nothing)]
347 --------------------------------------------------------------------}
348 -- | /O(log n)/. Delete a key and its value from the map. When the key is not
349 -- a member of the map, the original map is returned.
350 delete :: Ord k => k -> Map k a -> Map k a
355 -> case compare k kx of
356 LT -> balance kx x (delete k l) r
357 GT -> balance kx x l (delete k r)
360 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
361 -- a member of the map, the original map is returned.
362 adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
364 = adjustWithKey (\k x -> f x) k m
366 -- | /O(log n)/. Adjust a value at a specific key. When the key is not
367 -- a member of the map, the original map is returned.
368 adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
370 = updateWithKey (\k x -> Just (f k x)) k m
372 -- | /O(log n)/. The expression (@'update' f k map@) updates the value @x@
373 -- at @k@ (if it is in the map). If (@f x@) is 'Nothing', the element is
374 -- deleted. If it is (@'Just' y@), the key @k@ is bound to the new value @y@.
375 update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
377 = updateWithKey (\k x -> f x) k m
379 -- | /O(log n)/. The expression (@'updateWithKey' f k map@) updates the
380 -- value @x@ at @k@ (if it is in the map). If (@f k x@) is 'Nothing',
381 -- the element is deleted. If it is (@'Just' y@), the key @k@ is bound
382 -- to the new value @y@.
383 updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
388 -> case compare k kx of
389 LT -> balance kx x (updateWithKey f k l) r
390 GT -> balance kx x l (updateWithKey f k r)
392 Just x' -> Bin sx kx x' l r
395 -- | /O(log n)/. Lookup and update.
396 updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
397 updateLookupWithKey f k t
401 -> case compare k kx of
402 LT -> let (found,l') = updateLookupWithKey f k l in (found,balance kx x l' r)
403 GT -> let (found,r') = updateLookupWithKey f k r in (found,balance kx x l r')
405 Just x' -> (Just x',Bin sx kx x' l r)
406 Nothing -> (Just x,glue l r)
408 {--------------------------------------------------------------------
410 --------------------------------------------------------------------}
411 -- | /O(log n)/. Return the /index/ of a key. The index is a number from
412 -- /0/ up to, but not including, the 'size' of the map. Calls 'error' when
413 -- the key is not a 'member' of the map.
414 findIndex :: Ord k => k -> Map k a -> Int
416 = case lookupIndex k t of
417 Nothing -> error "Map.findIndex: element is not in the map"
420 -- | /O(log n)/. Lookup the /index/ of a key. The index is a number from
421 -- /0/ up to, but not including, the 'size' of the map.
422 lookupIndex :: (Monad m,Ord k) => k -> Map k a -> m Int
423 lookupIndex k t = case lookup 0 t of
424 Nothing -> fail "Data.Map.lookupIndex: Key not found."
427 lookup idx Tip = Nothing
428 lookup idx (Bin _ kx x l r)
429 = case compare k kx of
431 GT -> lookup (idx + size l + 1) r
432 EQ -> Just (idx + size l)
434 -- | /O(log n)/. Retrieve an element by /index/. Calls 'error' when an
435 -- invalid index is used.
436 elemAt :: Int -> Map k a -> (k,a)
437 elemAt i Tip = error "Map.elemAt: index out of range"
438 elemAt i (Bin _ kx x l r)
439 = case compare i sizeL of
441 GT -> elemAt (i-sizeL-1) r
446 -- | /O(log n)/. Update the element at /index/. Calls 'error' when an
447 -- invalid index is used.
448 updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
449 updateAt f i Tip = error "Map.updateAt: index out of range"
450 updateAt f i (Bin sx kx x l r)
451 = case compare i sizeL of
453 GT -> updateAt f (i-sizeL-1) r
455 Just x' -> Bin sx kx x' l r
460 -- | /O(log n)/. Delete the element at /index/.
461 -- Defined as (@'deleteAt' i map = 'updateAt' (\k x -> 'Nothing') i map@).
462 deleteAt :: Int -> Map k a -> Map k a
464 = updateAt (\k x -> Nothing) i map
467 {--------------------------------------------------------------------
469 --------------------------------------------------------------------}
470 -- | /O(log n)/. The minimal key of the map.
471 findMin :: Map k a -> (k,a)
472 findMin (Bin _ kx x Tip r) = (kx,x)
473 findMin (Bin _ kx x l r) = findMin l
474 findMin Tip = error "Map.findMin: empty tree has no minimal element"
476 -- | /O(log n)/. The maximal key of the map.
477 findMax :: Map k a -> (k,a)
478 findMax (Bin _ kx x l Tip) = (kx,x)
479 findMax (Bin _ kx x l r) = findMax r
480 findMax Tip = error "Map.findMax: empty tree has no maximal element"
482 -- | /O(log n)/. Delete the minimal key.
483 deleteMin :: Map k a -> Map k a
484 deleteMin (Bin _ kx x Tip r) = r
485 deleteMin (Bin _ kx x l r) = balance kx x (deleteMin l) r
488 -- | /O(log n)/. Delete the maximal key.
489 deleteMax :: Map k a -> Map k a
490 deleteMax (Bin _ kx x l Tip) = l
491 deleteMax (Bin _ kx x l r) = balance kx x l (deleteMax r)
494 -- | /O(log n)/. Update the value at the minimal key.
495 updateMin :: (a -> Maybe a) -> Map k a -> Map k a
497 = updateMinWithKey (\k x -> f x) m
499 -- | /O(log n)/. Update the value at the maximal key.
500 updateMax :: (a -> Maybe a) -> Map k a -> Map k a
502 = updateMaxWithKey (\k x -> f x) m
505 -- | /O(log n)/. Update the value at the minimal key.
506 updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
509 Bin sx kx x Tip r -> case f kx x of
511 Just x' -> Bin sx kx x' Tip r
512 Bin sx kx x l r -> balance kx x (updateMinWithKey f l) r
515 -- | /O(log n)/. Update the value at the maximal key.
516 updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
519 Bin sx kx x l Tip -> case f kx x of
521 Just x' -> Bin sx kx x' l Tip
522 Bin sx kx x l r -> balance kx x l (updateMaxWithKey f r)
526 {--------------------------------------------------------------------
528 --------------------------------------------------------------------}
529 -- | The union of a list of maps:
530 -- (@'unions' == 'Prelude.foldl' 'union' 'empty'@).
531 unions :: Ord k => [Map k a] -> Map k a
533 = foldlStrict union empty ts
535 -- | The union of a list of maps, with a combining operation:
536 -- (@'unionsWith' f == 'Prelude.foldl' ('unionWith' f) 'empty'@).
537 unionsWith :: Ord k => (a->a->a) -> [Map k a] -> Map k a
539 = foldlStrict (unionWith f) empty ts
542 -- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
543 -- It prefers @t1@ when duplicate keys are encountered,
544 -- i.e. (@'union' == 'unionWith' 'const'@).
545 -- The implementation uses the efficient /hedge-union/ algorithm.
546 -- Hedge-union is more efficient on (bigset `union` smallset)?
547 union :: Ord k => Map k a -> Map k a -> Map k a
551 | size t1 >= size t2 = hedgeUnionL (const LT) (const GT) t1 t2
552 | otherwise = hedgeUnionR (const LT) (const GT) t2 t1
554 -- left-biased hedge union
555 hedgeUnionL cmplo cmphi t1 Tip
557 hedgeUnionL cmplo cmphi Tip (Bin _ kx x l r)
558 = join kx x (filterGt cmplo l) (filterLt cmphi r)
559 hedgeUnionL cmplo cmphi (Bin _ kx x l r) t2
560 = join kx x (hedgeUnionL cmplo cmpkx l (trim cmplo cmpkx t2))
561 (hedgeUnionL cmpkx cmphi r (trim cmpkx cmphi t2))
563 cmpkx k = compare kx k
565 -- right-biased hedge union
566 hedgeUnionR cmplo cmphi t1 Tip
568 hedgeUnionR cmplo cmphi Tip (Bin _ kx x l r)
569 = join kx x (filterGt cmplo l) (filterLt cmphi r)
570 hedgeUnionR cmplo cmphi (Bin _ kx x l r) t2
571 = join kx newx (hedgeUnionR cmplo cmpkx l lt)
572 (hedgeUnionR cmpkx cmphi r gt)
574 cmpkx k = compare kx k
575 lt = trim cmplo cmpkx t2
576 (found,gt) = trimLookupLo kx cmphi t2
581 {--------------------------------------------------------------------
582 Union with a combining function
583 --------------------------------------------------------------------}
584 -- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
585 unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
587 = unionWithKey (\k x y -> f x y) m1 m2
590 -- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
591 -- Hedge-union is more efficient on (bigset `union` smallset).
592 unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
593 unionWithKey f Tip t2 = t2
594 unionWithKey f t1 Tip = t1
596 | size t1 >= size t2 = hedgeUnionWithKey f (const LT) (const GT) t1 t2
597 | otherwise = hedgeUnionWithKey flipf (const LT) (const GT) t2 t1
599 flipf k x y = f k y x
601 hedgeUnionWithKey f cmplo cmphi t1 Tip
603 hedgeUnionWithKey f cmplo cmphi Tip (Bin _ kx x l r)
604 = join kx x (filterGt cmplo l) (filterLt cmphi r)
605 hedgeUnionWithKey f cmplo cmphi (Bin _ kx x l r) t2
606 = join kx newx (hedgeUnionWithKey f cmplo cmpkx l lt)
607 (hedgeUnionWithKey f cmpkx cmphi r gt)
609 cmpkx k = compare kx k
610 lt = trim cmplo cmpkx t2
611 (found,gt) = trimLookupLo kx cmphi t2
616 {--------------------------------------------------------------------
618 --------------------------------------------------------------------}
619 -- | /O(n+m)/. Difference of two maps.
620 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
621 difference :: Ord k => Map k a -> Map k b -> Map k a
622 difference Tip t2 = Tip
623 difference t1 Tip = t1
624 difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
626 hedgeDiff cmplo cmphi Tip t
628 hedgeDiff cmplo cmphi (Bin _ kx x l r) Tip
629 = join kx x (filterGt cmplo l) (filterLt cmphi r)
630 hedgeDiff cmplo cmphi t (Bin _ kx x l r)
631 = merge (hedgeDiff cmplo cmpkx (trim cmplo cmpkx t) l)
632 (hedgeDiff cmpkx cmphi (trim cmpkx cmphi t) r)
634 cmpkx k = compare kx k
636 -- | /O(n+m)/. Difference with a combining function.
637 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
638 differenceWith :: Ord k => (a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
639 differenceWith f m1 m2
640 = differenceWithKey (\k x y -> f x y) m1 m2
642 -- | /O(n+m)/. Difference with a combining function. When two equal keys are
643 -- encountered, the combining function is applied to the key and both values.
644 -- If it returns 'Nothing', the element is discarded (proper set difference). If
645 -- it returns (@'Just' y@), the element is updated with a new value @y@.
646 -- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
647 differenceWithKey :: Ord k => (k -> a -> b -> Maybe a) -> Map k a -> Map k b -> Map k a
648 differenceWithKey f Tip t2 = Tip
649 differenceWithKey f t1 Tip = t1
650 differenceWithKey f t1 t2 = hedgeDiffWithKey f (const LT) (const GT) t1 t2
652 hedgeDiffWithKey f cmplo cmphi Tip t
654 hedgeDiffWithKey f cmplo cmphi (Bin _ kx x l r) Tip
655 = join kx x (filterGt cmplo l) (filterLt cmphi r)
656 hedgeDiffWithKey f cmplo cmphi t (Bin _ kx x l r)
658 Nothing -> merge tl tr
659 Just y -> case f kx y x of
660 Nothing -> merge tl tr
661 Just z -> join kx z tl tr
663 cmpkx k = compare kx k
664 lt = trim cmplo cmpkx t
665 (found,gt) = trimLookupLo kx cmphi t
666 tl = hedgeDiffWithKey f cmplo cmpkx lt l
667 tr = hedgeDiffWithKey f cmpkx cmphi gt r
671 {--------------------------------------------------------------------
673 --------------------------------------------------------------------}
674 -- | /O(n+m)/. Intersection of two maps. The values in the first
675 -- map are returned, i.e. (@'intersection' m1 m2 == 'intersectionWith' 'const' m1 m2@).
676 intersection :: Ord k => Map k a -> Map k b -> Map k a
678 = intersectionWithKey (\k x y -> x) m1 m2
680 -- | /O(n+m)/. Intersection with a combining function.
681 intersectionWith :: Ord k => (a -> b -> c) -> Map k a -> Map k b -> Map k c
682 intersectionWith f m1 m2
683 = intersectionWithKey (\k x y -> f x y) m1 m2
685 -- | /O(n+m)/. Intersection with a combining function.
686 -- Intersection is more efficient on (bigset `intersection` smallset)
687 intersectionWithKey :: Ord k => (k -> a -> b -> c) -> Map k a -> Map k b -> Map k c
688 intersectionWithKey f Tip t = Tip
689 intersectionWithKey f t Tip = Tip
690 intersectionWithKey f t1 t2
691 | size t1 >= size t2 = intersectWithKey f t1 t2
692 | otherwise = intersectWithKey flipf t2 t1
694 flipf k x y = f k y x
696 intersectWithKey f Tip t = Tip
697 intersectWithKey f t Tip = Tip
698 intersectWithKey f t (Bin _ kx x l r)
700 Nothing -> merge tl tr
701 Just y -> join kx (f kx y x) tl tr
703 (lt,found,gt) = splitLookup kx t
704 tl = intersectWithKey f lt l
705 tr = intersectWithKey f gt r
709 {--------------------------------------------------------------------
711 --------------------------------------------------------------------}
713 -- This function is defined as (@'isSubmapOf' = 'isSubmapOfBy' (==)@).
714 isSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
716 = isSubmapOfBy (==) m1 m2
719 The expression (@'isSubmapOfBy' f t1 t2@) returns 'True' if
720 all keys in @t1@ are in tree @t2@, and when @f@ returns 'True' when
721 applied to their respective values. For example, the following
722 expressions are all 'True':
724 > isSubmapOfBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
725 > isSubmapOfBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
726 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
728 But the following are all 'False':
730 > isSubmapOfBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
731 > isSubmapOfBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
732 > isSubmapOfBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
734 isSubmapOfBy :: Ord k => (a->b->Bool) -> Map k a -> Map k b -> Bool
736 = (size t1 <= size t2) && (submap' f t1 t2)
738 submap' f Tip t = True
739 submap' f t Tip = False
740 submap' f (Bin _ kx x l r) t
743 Just y -> f x y && submap' f l lt && submap' f r gt
745 (lt,found,gt) = splitLookup kx t
747 -- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
748 -- Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy' (==)@).
749 isProperSubmapOf :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
750 isProperSubmapOf m1 m2
751 = isProperSubmapOfBy (==) m1 m2
753 {- | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
754 The expression (@'isProperSubmapOfBy' f m1 m2@) returns 'True' when
755 @m1@ and @m2@ are not equal,
756 all keys in @m1@ are in @m2@, and when @f@ returns 'True' when
757 applied to their respective values. For example, the following
758 expressions are all 'True':
760 > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
761 > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
763 But the following are all 'False':
765 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
766 > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
767 > isProperSubmapOfBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
769 isProperSubmapOfBy :: Ord k => (a -> b -> Bool) -> Map k a -> Map k b -> Bool
770 isProperSubmapOfBy f t1 t2
771 = (size t1 < size t2) && (submap' f t1 t2)
773 {--------------------------------------------------------------------
775 --------------------------------------------------------------------}
776 -- | /O(n)/. Filter all values that satisfy the predicate.
777 filter :: Ord k => (a -> Bool) -> Map k a -> Map k a
779 = filterWithKey (\k x -> p x) m
781 -- | /O(n)/. Filter all keys\/values that satisfy the predicate.
782 filterWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> Map k a
783 filterWithKey p Tip = Tip
784 filterWithKey p (Bin _ kx x l r)
785 | p kx x = join kx x (filterWithKey p l) (filterWithKey p r)
786 | otherwise = merge (filterWithKey p l) (filterWithKey p r)
789 -- | /O(n)/. partition the map according to a predicate. The first
790 -- map contains all elements that satisfy the predicate, the second all
791 -- elements that fail the predicate. See also 'split'.
792 partition :: Ord k => (a -> Bool) -> Map k a -> (Map k a,Map k a)
794 = partitionWithKey (\k x -> p x) m
796 -- | /O(n)/. partition the map according to a predicate. The first
797 -- map contains all elements that satisfy the predicate, the second all
798 -- elements that fail the predicate. See also 'split'.
799 partitionWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
800 partitionWithKey p Tip = (Tip,Tip)
801 partitionWithKey p (Bin _ kx x l r)
802 | p kx x = (join kx x l1 r1,merge l2 r2)
803 | otherwise = (merge l1 r1,join kx x l2 r2)
805 (l1,l2) = partitionWithKey p l
806 (r1,r2) = partitionWithKey p r
809 {--------------------------------------------------------------------
811 --------------------------------------------------------------------}
812 -- | /O(n)/. Map a function over all values in the map.
813 map :: (a -> b) -> Map k a -> Map k b
815 = mapWithKey (\k x -> f x) m
817 -- | /O(n)/. Map a function over all values in the map.
818 mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
819 mapWithKey f Tip = Tip
820 mapWithKey f (Bin sx kx x l r)
821 = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
823 -- | /O(n)/. The function 'mapAccum' threads an accumulating
824 -- argument through the map in ascending order of keys.
825 mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
827 = mapAccumWithKey (\a k x -> f a x) a m
829 -- | /O(n)/. The function 'mapAccumWithKey' threads an accumulating
830 -- argument through the map in ascending order of keys.
831 mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
832 mapAccumWithKey f a t
835 -- | /O(n)/. The function 'mapAccumL' threads an accumulating
836 -- argument throught the map in ascending order of keys.
837 mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
842 -> let (a1,l') = mapAccumL f a l
844 (a3,r') = mapAccumL f a2 r
845 in (a3,Bin sx kx x' l' r')
847 -- | /O(n)/. The function 'mapAccumR' threads an accumulating
848 -- argument throught the map in descending order of keys.
849 mapAccumR :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
854 -> let (a1,r') = mapAccumR f a r
856 (a3,l') = mapAccumR f a2 l
857 in (a3,Bin sx kx x' l' r')
860 -- @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
862 -- The size of the result may be smaller if @f@ maps two or more distinct
863 -- keys to the same new key. In this case the value at the smallest of
864 -- these keys is retained.
866 mapKeys :: Ord k2 => (k1->k2) -> Map k1 a -> Map k2 a
867 mapKeys = mapKeysWith (\x y->x)
870 -- @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
872 -- The size of the result may be smaller if @f@ maps two or more distinct
873 -- keys to the same new key. In this case the associated values will be
874 -- combined using @c@.
876 mapKeysWith :: Ord k2 => (a -> a -> a) -> (k1->k2) -> Map k1 a -> Map k2 a
877 mapKeysWith c f = fromListWith c . List.map fFirst . toList
878 where fFirst (x,y) = (f x, y)
882 -- @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
883 -- is strictly monotonic.
884 -- /The precondition is not checked./
885 -- Semi-formally, we have:
887 -- > and [x < y ==> f x < f y | x <- ls, y <- ls]
888 -- > ==> mapKeysMonotonic f s == mapKeys f s
889 -- > where ls = keys s
891 mapKeysMonotonic :: (k1->k2) -> Map k1 a -> Map k2 a
892 mapKeysMonotonic f Tip = Tip
893 mapKeysMonotonic f (Bin sz k x l r) =
894 Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)
896 {--------------------------------------------------------------------
898 --------------------------------------------------------------------}
900 -- | /O(n)/. Fold the values in the map, such that
901 -- @'fold' f z == 'Prelude.foldr' f z . 'elems'@.
904 -- > elems map = fold (:) [] map
906 fold :: (a -> b -> b) -> b -> Map k a -> b
908 = foldWithKey (\k x z -> f x z) z m
910 -- | /O(n)/. Fold the keys and values in the map, such that
911 -- @'foldWithKey' f z == 'Prelude.foldr' ('uncurry' f) z . 'toAscList'@.
914 -- > keys map = foldWithKey (\k x ks -> k:ks) [] map
916 foldWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
920 -- | /O(n)/. In-order fold.
921 foldi :: (k -> a -> b -> b -> b) -> b -> Map k a -> b
923 foldi f z (Bin _ kx x l r) = f kx x (foldi f z l) (foldi f z r)
925 -- | /O(n)/. Post-order fold.
926 foldr :: (k -> a -> b -> b) -> b -> Map k a -> b
928 foldr f z (Bin _ kx x l r) = foldr f (f kx x (foldr f z r)) l
930 -- | /O(n)/. Pre-order fold.
931 foldl :: (b -> k -> a -> b) -> b -> Map k a -> b
933 foldl f z (Bin _ kx x l r) = foldl f (f (foldl f z l) kx x) r
935 {--------------------------------------------------------------------
937 --------------------------------------------------------------------}
939 -- Return all elements of the map in the ascending order of their keys.
940 elems :: Map k a -> [a]
942 = [x | (k,x) <- assocs m]
944 -- | /O(n)/. Return all keys of the map in ascending order.
945 keys :: Map k a -> [k]
947 = [k | (k,x) <- assocs m]
949 -- | /O(n)/. The set of all keys of the map.
950 keysSet :: Map k a -> Set.Set k
951 keysSet m = Set.fromDistinctAscList (keys m)
953 -- | /O(n)/. Return all key\/value pairs in the map in ascending key order.
954 assocs :: Map k a -> [(k,a)]
958 {--------------------------------------------------------------------
960 use [foldlStrict] to reduce demand on the control-stack
961 --------------------------------------------------------------------}
962 -- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
963 fromList :: Ord k => [(k,a)] -> Map k a
965 = foldlStrict ins empty xs
967 ins t (k,x) = insert k x t
969 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
970 fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
972 = fromListWithKey (\k x y -> f x y) xs
974 -- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
975 fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
977 = foldlStrict ins empty xs
979 ins t (k,x) = insertWithKey f k x t
981 -- | /O(n)/. Convert to a list of key\/value pairs.
982 toList :: Map k a -> [(k,a)]
983 toList t = toAscList t
985 -- | /O(n)/. Convert to an ascending list.
986 toAscList :: Map k a -> [(k,a)]
987 toAscList t = foldr (\k x xs -> (k,x):xs) [] t
990 toDescList :: Map k a -> [(k,a)]
991 toDescList t = foldl (\xs k x -> (k,x):xs) [] t
994 {--------------------------------------------------------------------
995 Building trees from ascending/descending lists can be done in linear time.
997 Note that if [xs] is ascending that:
998 fromAscList xs == fromList xs
999 fromAscListWith f xs == fromListWith f xs
1000 --------------------------------------------------------------------}
1001 -- | /O(n)/. Build a map from an ascending list in linear time.
1002 -- /The precondition (input list is ascending) is not checked./
1003 fromAscList :: Eq k => [(k,a)] -> Map k a
1005 = fromAscListWithKey (\k x y -> x) xs
1007 -- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
1008 -- /The precondition (input list is ascending) is not checked./
1009 fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
1010 fromAscListWith f xs
1011 = fromAscListWithKey (\k x y -> f x y) xs
1013 -- | /O(n)/. Build a map from an ascending list in linear time with a
1014 -- combining function for equal keys.
1015 -- /The precondition (input list is ascending) is not checked./
1016 fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
1017 fromAscListWithKey f xs
1018 = fromDistinctAscList (combineEq f xs)
1020 -- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
1025 (x:xx) -> combineEq' x xx
1027 combineEq' z [] = [z]
1028 combineEq' z@(kz,zz) (x@(kx,xx):xs)
1029 | kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs
1030 | otherwise = z:combineEq' x xs
1033 -- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
1034 -- /The precondition is not checked./
1035 fromDistinctAscList :: [(k,a)] -> Map k a
1036 fromDistinctAscList xs
1037 = build const (length xs) xs
1039 -- 1) use continutations so that we use heap space instead of stack space.
1040 -- 2) special case for n==5 to build bushier trees.
1041 build c 0 xs = c Tip xs
1042 build c 5 xs = case xs of
1043 ((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
1044 -> c (bin k4 x4 (bin k2 x2 (singleton k1 x1) (singleton k3 x3)) (singleton k5 x5)) xx
1045 build c n xs = seq nr $ build (buildR nr c) nl xs
1050 buildR n c l ((k,x):ys) = build (buildB l k x c) n ys
1051 buildB l k x c r zs = c (bin k x l r) zs
1055 {--------------------------------------------------------------------
1056 Utility functions that return sub-ranges of the original
1057 tree. Some functions take a comparison function as argument to
1058 allow comparisons against infinite values. A function [cmplo k]
1059 should be read as [compare lo k].
1061 [trim cmplo cmphi t] A tree that is either empty or where [cmplo k == LT]
1062 and [cmphi k == GT] for the key [k] of the root.
1063 [filterGt cmp t] A tree where for all keys [k]. [cmp k == LT]
1064 [filterLt cmp t] A tree where for all keys [k]. [cmp k == GT]
1066 [split k t] Returns two trees [l] and [r] where all keys
1067 in [l] are <[k] and all keys in [r] are >[k].
1068 [splitLookup k t] Just like [split] but also returns whether [k]
1069 was found in the tree.
1070 --------------------------------------------------------------------}
1072 {--------------------------------------------------------------------
1073 [trim lo hi t] trims away all subtrees that surely contain no
1074 values between the range [lo] to [hi]. The returned tree is either
1075 empty or the key of the root is between @lo@ and @hi@.
1076 --------------------------------------------------------------------}
1077 trim :: (k -> Ordering) -> (k -> Ordering) -> Map k a -> Map k a
1078 trim cmplo cmphi Tip = Tip
1079 trim cmplo cmphi t@(Bin sx kx x l r)
1081 LT -> case cmphi kx of
1083 le -> trim cmplo cmphi l
1084 ge -> trim cmplo cmphi r
1086 trimLookupLo :: Ord k => k -> (k -> Ordering) -> Map k a -> (Maybe a, Map k a)
1087 trimLookupLo lo cmphi Tip = (Nothing,Tip)
1088 trimLookupLo lo cmphi t@(Bin sx kx x l r)
1089 = case compare lo kx of
1090 LT -> case cmphi kx of
1091 GT -> (lookup lo t, t)
1092 le -> trimLookupLo lo cmphi l
1093 GT -> trimLookupLo lo cmphi r
1094 EQ -> (Just x,trim (compare lo) cmphi r)
1097 {--------------------------------------------------------------------
1098 [filterGt k t] filter all keys >[k] from tree [t]
1099 [filterLt k t] filter all keys <[k] from tree [t]
1100 --------------------------------------------------------------------}
1101 filterGt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1102 filterGt cmp Tip = Tip
1103 filterGt cmp (Bin sx kx x l r)
1105 LT -> join kx x (filterGt cmp l) r
1106 GT -> filterGt cmp r
1109 filterLt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
1110 filterLt cmp Tip = Tip
1111 filterLt cmp (Bin sx kx x l r)
1113 LT -> filterLt cmp l
1114 GT -> join kx x l (filterLt cmp r)
1117 {--------------------------------------------------------------------
1119 --------------------------------------------------------------------}
1120 -- | /O(log n)/. The expression (@'split' k map@) is a pair @(map1,map2)@ where
1121 -- 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@.
1122 split :: Ord k => k -> Map k a -> (Map k a,Map k a)
1123 split k Tip = (Tip,Tip)
1124 split k (Bin sx kx x l r)
1125 = case compare k kx of
1126 LT -> let (lt,gt) = split k l in (lt,join kx x gt r)
1127 GT -> let (lt,gt) = split k r in (join kx x l lt,gt)
1130 -- | /O(log n)/. The expression (@'splitLookup' k map@) splits a map just
1131 -- like 'split' but also returns @'lookup' k map@.
1132 splitLookup :: Ord k => k -> Map k a -> (Map k a,Maybe a,Map k a)
1133 splitLookup k Tip = (Tip,Nothing,Tip)
1134 splitLookup k (Bin sx kx x l r)
1135 = case compare k kx of
1136 LT -> let (lt,z,gt) = splitLookup k l in (lt,z,join kx x gt r)
1137 GT -> let (lt,z,gt) = splitLookup k r in (join kx x l lt,z,gt)
1140 {--------------------------------------------------------------------
1141 Utility functions that maintain the balance properties of the tree.
1142 All constructors assume that all values in [l] < [k] and all values
1143 in [r] > [k], and that [l] and [r] are valid trees.
1145 In order of sophistication:
1146 [Bin sz k x l r] The type constructor.
1147 [bin k x l r] Maintains the correct size, assumes that both [l]
1148 and [r] are balanced with respect to each other.
1149 [balance k x l r] Restores the balance and size.
1150 Assumes that the original tree was balanced and
1151 that [l] or [r] has changed by at most one element.
1152 [join k x l r] Restores balance and size.
1154 Furthermore, we can construct a new tree from two trees. Both operations
1155 assume that all values in [l] < all values in [r] and that [l] and [r]
1157 [glue l r] Glues [l] and [r] together. Assumes that [l] and
1158 [r] are already balanced with respect to each other.
1159 [merge l r] Merges two trees and restores balance.
1161 Note: in contrast to Adam's paper, we use (<=) comparisons instead
1162 of (<) comparisons in [join], [merge] and [balance].
1163 Quickcheck (on [difference]) showed that this was necessary in order
1164 to maintain the invariants. It is quite unsatisfactory that I haven't
1165 been able to find out why this is actually the case! Fortunately, it
1166 doesn't hurt to be a bit more conservative.
1167 --------------------------------------------------------------------}
1169 {--------------------------------------------------------------------
1171 --------------------------------------------------------------------}
1172 join :: Ord k => k -> a -> Map k a -> Map k a -> Map k a
1173 join kx x Tip r = insertMin kx x r
1174 join kx x l Tip = insertMax kx x l
1175 join kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
1176 | delta*sizeL <= sizeR = balance kz z (join kx x l lz) rz
1177 | delta*sizeR <= sizeL = balance ky y ly (join kx x ry r)
1178 | otherwise = bin kx x l r
1181 -- insertMin and insertMax don't perform potentially expensive comparisons.
1182 insertMax,insertMin :: k -> a -> Map k a -> Map k a
1185 Tip -> singleton kx x
1187 -> balance ky y l (insertMax kx x r)
1191 Tip -> singleton kx x
1193 -> balance ky y (insertMin kx x l) r
1195 {--------------------------------------------------------------------
1196 [merge l r]: merges two trees.
1197 --------------------------------------------------------------------}
1198 merge :: Map k a -> Map k a -> Map k a
1201 merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
1202 | delta*sizeL <= sizeR = balance ky y (merge l ly) ry
1203 | delta*sizeR <= sizeL = balance kx x lx (merge rx r)
1204 | otherwise = glue l r
1206 {--------------------------------------------------------------------
1207 [glue l r]: glues two trees together.
1208 Assumes that [l] and [r] are already balanced with respect to each other.
1209 --------------------------------------------------------------------}
1210 glue :: Map k a -> Map k a -> Map k a
1214 | size l > size r = let ((km,m),l') = deleteFindMax l in balance km m l' r
1215 | otherwise = let ((km,m),r') = deleteFindMin r in balance km m l r'
1218 -- | /O(log n)/. Delete and find the minimal element.
1219 deleteFindMin :: Map k a -> ((k,a),Map k a)
1222 Bin _ k x Tip r -> ((k,x),r)
1223 Bin _ k x l r -> let (km,l') = deleteFindMin l in (km,balance k x l' r)
1224 Tip -> (error "Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
1226 -- | /O(log n)/. Delete and find the maximal element.
1227 deleteFindMax :: Map k a -> ((k,a),Map k a)
1230 Bin _ k x l Tip -> ((k,x),l)
1231 Bin _ k x l r -> let (km,r') = deleteFindMax r in (km,balance k x l r')
1232 Tip -> (error "Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
1235 {--------------------------------------------------------------------
1236 [balance l x r] balances two trees with value x.
1237 The sizes of the trees should balance after decreasing the
1238 size of one of them. (a rotation).
1240 [delta] is the maximal relative difference between the sizes of
1241 two trees, it corresponds with the [w] in Adams' paper.
1242 [ratio] is the ratio between an outer and inner sibling of the
1243 heavier subtree in an unbalanced setting. It determines
1244 whether a double or single rotation should be performed
1245 to restore balance. It is correspondes with the inverse
1246 of $\alpha$ in Adam's article.
1249 - [delta] should be larger than 4.646 with a [ratio] of 2.
1250 - [delta] should be larger than 3.745 with a [ratio] of 1.534.
1252 - A lower [delta] leads to a more 'perfectly' balanced tree.
1253 - A higher [delta] performs less rebalancing.
1255 - Balancing is automatic for random data and a balancing
1256 scheme is only necessary to avoid pathological worst cases.
1257 Almost any choice will do, and in practice, a rather large
1258 [delta] may perform better than smaller one.
1260 Note: in contrast to Adam's paper, we use a ratio of (at least) [2]
1261 to decide whether a single or double rotation is needed. Allthough
1262 he actually proves that this ratio is needed to maintain the
1263 invariants, his implementation uses an invalid ratio of [1].
1264 --------------------------------------------------------------------}
1269 balance :: k -> a -> Map k a -> Map k a -> Map k a
1271 | sizeL + sizeR <= 1 = Bin sizeX k x l r
1272 | sizeR >= delta*sizeL = rotateL k x l r
1273 | sizeL >= delta*sizeR = rotateR k x l r
1274 | otherwise = Bin sizeX k x l r
1278 sizeX = sizeL + sizeR + 1
1281 rotateL k x l r@(Bin _ _ _ ly ry)
1282 | size ly < ratio*size ry = singleL k x l r
1283 | otherwise = doubleL k x l r
1285 rotateR k x l@(Bin _ _ _ ly ry) r
1286 | size ry < ratio*size ly = singleR k x l r
1287 | otherwise = doubleR k x l r
1290 singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
1291 singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
1293 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)
1294 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)
1297 {--------------------------------------------------------------------
1298 The bin constructor maintains the size of the tree
1299 --------------------------------------------------------------------}
1300 bin :: k -> a -> Map k a -> Map k a -> Map k a
1302 = Bin (size l + size r + 1) k x l r
1305 {--------------------------------------------------------------------
1306 Eq converts the tree to a list. In a lazy setting, this
1307 actually seems one of the faster methods to compare two trees
1308 and it is certainly the simplest :-)
1309 --------------------------------------------------------------------}
1310 instance (Eq k,Eq a) => Eq (Map k a) where
1311 t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
1313 {--------------------------------------------------------------------
1315 --------------------------------------------------------------------}
1317 instance (Ord k, Ord v) => Ord (Map k v) where
1318 compare m1 m2 = compare (toAscList m1) (toAscList m2)
1320 {--------------------------------------------------------------------
1322 --------------------------------------------------------------------}
1323 instance Functor (Map k) where
1326 instance Traversable (Map k) where
1327 traverse f Tip = pure Tip
1328 traverse f (Bin s k v l r)
1329 = flip (Bin s k) <$> traverse f l <*> f v <*> traverse f r
1331 instance Foldable (Map k) where
1332 foldMap _f Tip = mempty
1333 foldMap f (Bin _s _k v l r)
1334 = foldMap f l `mappend` f v `mappend` foldMap f r
1336 {--------------------------------------------------------------------
1338 --------------------------------------------------------------------}
1339 instance (Ord k, Read k, Read e) => Read (Map k e) where
1340 #ifdef __GLASGOW_HASKELL__
1341 readPrec = parens $ prec 10 $ do
1342 Ident "fromList" <- lexP
1344 return (fromList xs)
1346 readListPrec = readListPrecDefault
1348 readsPrec p = readParen (p > 10) $ \ r -> do
1349 ("fromList",s) <- lex r
1351 return (fromList xs,t)
1354 -- parses a pair of things with the syntax a:=b
1355 readPair :: (Read a, Read b) => ReadS (a,b)
1356 readPair s = do (a, ct1) <- reads s
1357 (":=", ct2) <- lex ct1
1358 (b, ct3) <- reads ct2
1361 {--------------------------------------------------------------------
1363 --------------------------------------------------------------------}
1364 instance (Show k, Show a) => Show (Map k a) where
1365 showsPrec d m = showParen (d > 10) $
1366 showString "fromList " . shows (toList m)
1368 showMap :: (Show k,Show a) => [(k,a)] -> ShowS
1372 = showChar '{' . showElem x . showTail xs
1374 showTail [] = showChar '}'
1375 showTail (x:xs) = showString ", " . showElem x . showTail xs
1377 showElem (k,x) = shows k . showString " := " . shows x
1380 -- | /O(n)/. Show the tree that implements the map. The tree is shown
1381 -- in a compressed, hanging format.
1382 showTree :: (Show k,Show a) => Map k a -> String
1384 = showTreeWith showElem True False m
1386 showElem k x = show k ++ ":=" ++ show x
1389 {- | /O(n)/. The expression (@'showTreeWith' showelem hang wide map@) shows
1390 the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
1391 'True', a /hanging/ tree is shown otherwise a rotated tree is shown. If
1392 @wide@ is 'True', an extra wide version is shown.
1394 > Map> let t = fromDistinctAscList [(x,()) | x <- [1..5]]
1395 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False t
1402 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True t
1413 > Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True t
1425 showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
1426 showTreeWith showelem hang wide t
1427 | hang = (showsTreeHang showelem wide [] t) ""
1428 | otherwise = (showsTree showelem wide [] [] t) ""
1430 showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
1431 showsTree showelem wide lbars rbars t
1433 Tip -> showsBars lbars . showString "|\n"
1435 -> showsBars lbars . showString (showelem kx x) . showString "\n"
1437 -> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
1438 showWide wide rbars .
1439 showsBars lbars . showString (showelem kx x) . showString "\n" .
1440 showWide wide lbars .
1441 showsTree showelem wide (withEmpty lbars) (withBar lbars) l
1443 showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
1444 showsTreeHang showelem wide bars t
1446 Tip -> showsBars bars . showString "|\n"
1448 -> showsBars bars . showString (showelem kx x) . showString "\n"
1450 -> showsBars bars . showString (showelem kx x) . showString "\n" .
1451 showWide wide bars .
1452 showsTreeHang showelem wide (withBar bars) l .
1453 showWide wide bars .
1454 showsTreeHang showelem wide (withEmpty bars) r
1458 | wide = showString (concat (reverse bars)) . showString "|\n"
1461 showsBars :: [String] -> ShowS
1465 _ -> showString (concat (reverse (tail bars))) . showString node
1468 withBar bars = "| ":bars
1469 withEmpty bars = " ":bars
1471 {--------------------------------------------------------------------
1473 --------------------------------------------------------------------}
1475 #include "Typeable.h"
1476 INSTANCE_TYPEABLE2(Map,mapTc,"Map")
1478 {--------------------------------------------------------------------
1480 --------------------------------------------------------------------}
1481 -- | /O(n)/. Test if the internal map structure is valid.
1482 valid :: Ord k => Map k a -> Bool
1484 = balanced t && ordered t && validsize t
1487 = bounded (const True) (const True) t
1492 Bin sz kx x l r -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
1494 -- | Exported only for "Debug.QuickCheck"
1495 balanced :: Map k a -> Bool
1499 Bin sz kx x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
1500 balanced l && balanced r
1504 = (realsize t == Just (size t))
1509 Bin sz kx x l r -> case (realsize l,realsize r) of
1510 (Just n,Just m) | n+m+1 == sz -> Just sz
1513 {--------------------------------------------------------------------
1515 --------------------------------------------------------------------}
1519 (x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
1523 {--------------------------------------------------------------------
1525 --------------------------------------------------------------------}
1526 testTree xs = fromList [(x,"*") | x <- xs]
1527 test1 = testTree [1..20]
1528 test2 = testTree [30,29..10]
1529 test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
1531 {--------------------------------------------------------------------
1533 --------------------------------------------------------------------}
1538 { configMaxTest = 500
1539 , configMaxFail = 5000
1540 , configSize = \n -> (div n 2 + 3)
1541 , configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
1545 {--------------------------------------------------------------------
1546 Arbitrary, reasonably balanced trees
1547 --------------------------------------------------------------------}
1548 instance (Enum k,Arbitrary a) => Arbitrary (Map k a) where
1549 arbitrary = sized (arbtree 0 maxkey)
1550 where maxkey = 10000
1552 arbtree :: (Enum k,Arbitrary a) => Int -> Int -> Int -> Gen (Map k a)
1554 | n <= 0 = return Tip
1555 | lo >= hi = return Tip
1556 | otherwise = do{ x <- arbitrary
1557 ; i <- choose (lo,hi)
1558 ; m <- choose (1,30)
1559 ; let (ml,mr) | m==(1::Int)= (1,2)
1563 ; l <- arbtree lo (i-1) (n `div` ml)
1564 ; r <- arbtree (i+1) hi (n `div` mr)
1565 ; return (bin (toEnum i) x l r)
1569 {--------------------------------------------------------------------
1571 --------------------------------------------------------------------}
1572 forValid :: (Show k,Enum k,Show a,Arbitrary a,Testable b) => (Map k a -> b) -> Property
1574 = forAll arbitrary $ \t ->
1575 -- classify (balanced t) "balanced" $
1576 classify (size t == 0) "empty" $
1577 classify (size t > 0 && size t <= 10) "small" $
1578 classify (size t > 10 && size t <= 64) "medium" $
1579 classify (size t > 64) "large" $
1582 forValidIntTree :: Testable a => (Map Int Int -> a) -> Property
1586 forValidUnitTree :: Testable a => (Map Int () -> a) -> Property
1592 = forValidUnitTree $ \t -> valid t
1594 {--------------------------------------------------------------------
1595 Single, Insert, Delete
1596 --------------------------------------------------------------------}
1597 prop_Single :: Int -> Int -> Bool
1599 = (insert k x empty == singleton k x)
1601 prop_InsertValid :: Int -> Property
1603 = forValidUnitTree $ \t -> valid (insert k () t)
1605 prop_InsertDelete :: Int -> Map Int () -> Property
1606 prop_InsertDelete k t
1607 = (lookup k t == Nothing) ==> delete k (insert k () t) == t
1609 prop_DeleteValid :: Int -> Property
1611 = forValidUnitTree $ \t ->
1612 valid (delete k (insert k () t))
1614 {--------------------------------------------------------------------
1616 --------------------------------------------------------------------}
1617 prop_Join :: Int -> Property
1619 = forValidUnitTree $ \t ->
1620 let (l,r) = split k t
1621 in valid (join k () l r)
1623 prop_Merge :: Int -> Property
1625 = forValidUnitTree $ \t ->
1626 let (l,r) = split k t
1627 in valid (merge l r)
1630 {--------------------------------------------------------------------
1632 --------------------------------------------------------------------}
1633 prop_UnionValid :: Property
1635 = forValidUnitTree $ \t1 ->
1636 forValidUnitTree $ \t2 ->
1639 prop_UnionInsert :: Int -> Int -> Map Int Int -> Bool
1640 prop_UnionInsert k x t
1641 = union (singleton k x) t == insert k x t
1643 prop_UnionAssoc :: Map Int Int -> Map Int Int -> Map Int Int -> Bool
1644 prop_UnionAssoc t1 t2 t3
1645 = union t1 (union t2 t3) == union (union t1 t2) t3
1647 prop_UnionComm :: Map Int Int -> Map Int Int -> Bool
1648 prop_UnionComm t1 t2
1649 = (union t1 t2 == unionWith (\x y -> y) t2 t1)
1652 = forValidIntTree $ \t1 ->
1653 forValidIntTree $ \t2 ->
1654 valid (unionWithKey (\k x y -> x+y) t1 t2)
1656 prop_UnionWith :: [(Int,Int)] -> [(Int,Int)] -> Bool
1657 prop_UnionWith xs ys
1658 = sum (elems (unionWith (+) (fromListWith (+) xs) (fromListWith (+) ys)))
1659 == (sum (Prelude.map snd xs) + sum (Prelude.map snd ys))
1662 = forValidUnitTree $ \t1 ->
1663 forValidUnitTree $ \t2 ->
1664 valid (difference t1 t2)
1666 prop_Diff :: [(Int,Int)] -> [(Int,Int)] -> Bool
1668 = List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys)))
1669 == List.sort ((List.\\) (nub (Prelude.map fst xs)) (nub (Prelude.map fst ys)))
1672 = forValidUnitTree $ \t1 ->
1673 forValidUnitTree $ \t2 ->
1674 valid (intersection t1 t2)
1676 prop_Int :: [(Int,Int)] -> [(Int,Int)] -> Bool
1678 = List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys)))
1679 == List.sort (nub ((List.intersect) (Prelude.map fst xs) (Prelude.map fst ys)))
1681 {--------------------------------------------------------------------
1683 --------------------------------------------------------------------}
1685 = forAll (choose (5,100)) $ \n ->
1686 let xs = [(x,()) | x <- [0..n::Int]]
1687 in fromAscList xs == fromList xs
1689 prop_List :: [Int] -> Bool
1691 = (sort (nub xs) == [x | (x,()) <- toList (fromList [(x,()) | x <- xs])])