import Prelude hiding (lookup,map,filter)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(log n)/. See 'find'.
(!) :: Ord k => Map k a -> k -> a
-- | /O(n+m)/. See 'difference'.
(\\) :: Ord k => Map k a -> Map k a -> Map k a
m1 \\ m2 = difference m1 m2
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | A Map from keys @k@ and values @a@.
| Bin !Size !k a !(Map k a) !(Map k a)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(1)/. Is the map empty?
isEmpty :: Map k a -> Bool
-- | /O(1)/. The number of elements in the map.
-- | /O(log n)/. Lookup the value of key in the map.
lookup :: Ord k => k -> Map k a -> Maybe a
-- | /O(log n)/. Is the key a member of the map?
member :: Ord k => k -> Map k a -> Bool
-- | /O(log n)/. Find the value of a key. Calls @error@ when the element can not be found.
find :: Ord k => k -> Map k a -> a
Nothing -> error "
Map.find: element not in the map"
-- | /O(log n)/. The expression @(findWithDefault def k map)@ returns the value of key @k@ or returns @def@ when
-- the key is not in the map.
findWithDefault :: Ord k => a -> k -> Map k a -> a
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(1)/. Create an empty map.
-- | /O(1)/. Create a map with a single element.
single :: k -> a -> Map k a
{--------------------------------------------------------------------
[insert] is the inlined version of [insertWith (\k x y -> x)]
--------------------------------------------------------------------}
-- | /O(log n)/. Insert a new key and value in the map.
insert :: Ord k => k -> a -> Map k a -> Map k a
LT -> balance ky y (insert kx x l) r
GT -> balance ky y l (insert kx x r)
-- | /O(log n)/. Insert with a combining function.
insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
= insertWithKey (\k x y -> f x y) k x m
-- | /O(log n)/. Insert with a combining function.
insertWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> Map k a
LT -> balance ky y (insertWithKey f kx x l) r
GT -> balance ky y l (insertWithKey f kx x r)
EQ -> Bin sy ky (f ky x y) l r
-- | /O(log n)/. The expression (@insertLookupWithKey f k x map@) is a pair where
-- the first element is equal to (@lookup k map@) and the second element
-- equal to (@insertWithKey f k x map@).
insertLookupWithKey :: Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a,Map k a)
insertLookupWithKey f kx x t
Tip -> (Nothing, single kx x)
LT -> let (found,l') = insertLookupWithKey f kx x l in (found,balance ky y l' r)
GT -> let (found,r') = insertLookupWithKey f kx x r in (found,balance ky y l r')
EQ -> (Just y, Bin sy ky (f ky x y) l r)
{--------------------------------------------------------------------
[delete] is the inlined version of [deleteWith (\k x -> Nothing)]
--------------------------------------------------------------------}
-- | /O(log n)/. Delete a key and its value from the map. When the key is not
-- a member of the map, the original map is returned.
delete :: Ord k => k -> Map k a -> Map k a
LT -> balance kx x (delete k l) r
GT -> balance kx x l (delete k r)
-- | /O(log n)/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
adjust :: Ord k => (a -> a) -> k -> Map k a -> Map k a
= adjustWithKey (\k x -> f x) k m
-- | /O(log n)/. Adjust a value at a specific key. When the key is not
-- a member of the map, the original map is returned.
adjustWithKey :: Ord k => (k -> a -> a) -> k -> Map k a -> Map k a
= updateWithKey (\k x -> Just (f k x)) k m
-- | /O(log n)/. The expression (@update f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f x@) is @Nothing@, the element is
-- deleted. If it is (@Just y@), the key @k@ is bound to the new value @y@.
update :: Ord k => (a -> Maybe a) -> k -> Map k a -> Map k a
= updateWithKey (\k x -> f x) k m
-- | /O(log n)/. The expression (@update f k map@) updates the value @x@
-- at @k@ (if it is in the map). If (@f k x@) is @Nothing@, the element is
-- deleted. If it is (@Just y@), the key @k@ is bound to the new value @y@.
updateWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> Map k a
LT -> balance kx x (updateWithKey f k l) r
GT -> balance kx x l (updateWithKey f k r)
Just x' -> Bin sx kx x' l r
-- | /O(log n)/. Lookup and update.
updateLookupWithKey :: Ord k => (k -> a -> Maybe a) -> k -> Map k a -> (Maybe a,Map k a)
updateLookupWithKey f k t
LT -> let (found,l') = updateLookupWithKey f k l in (found,balance kx x l' r)
GT -> let (found,r') = updateLookupWithKey f k r in (found,balance kx x l r')
Just x' -> (Just x',Bin sx kx x' l r)
Nothing -> (Just x,glue l r)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(log n)/. Return the /index/ of a key. The index is a number from
-- /0/ up to, but not including, the 'size' of the map. Calls 'error' when
-- the key is not a 'member' of the map.
findIndex :: Ord k => k -> Map k a -> Int
= case lookupIndex k t of
-- | /O(log n)/. Lookup the /index/ of a key. The index is a number from
-- /0/ up to, but not including, the 'size' of the map.
lookupIndex :: Ord k => k -> Map k a -> Maybe Int
lookup idx (Bin _ kx x l r)
GT -> lookup (idx + size l + 1) r
EQ -> Just (idx + size l)
-- | /O(log n)/. Retrieve an element by /index/. Calls 'error' when an
-- invalid index is used.
elemAt :: Int -> Map k a -> (k,a)
elemAt i Tip = error "
Map.elemAt: index out of range"
elemAt i (Bin _ kx x l r)
= case compare i sizeL of
GT -> elemAt (i-sizeL-1) r
-- | /O(log n)/. Update the element at /index/. Calls 'error' when an
-- invalid index is used.
updateAt :: (k -> a -> Maybe a) -> Int -> Map k a -> Map k a
updateAt f i (Bin sx kx x l r)
= case compare i sizeL of
GT -> updateAt f (i-sizeL-1) r
Just x' -> Bin sx kx x' l r
-- | /O(log n)/. Delete the element at /index/. Defined as (@deleteAt i map = updateAt (\k x -> Nothing) i map@).
deleteAt :: Int -> Map k a -> Map k a
= updateAt (\k x -> Nothing) i map
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(log n)/. The minimal key of the map.
findMin :: Map k a -> (k,a)
findMin (Bin _ kx x Tip r) = (kx,x)
findMin (Bin _ kx x l r) = findMin l
findMin Tip = error "
Map.findMin: empty tree has no minimal element"
-- | /O(log n)/. The maximal key of the map.
findMax :: Map k a -> (k,a)
findMax (Bin _ kx x l Tip) = (kx,x)
findMax (Bin _ kx x l r) = findMax r
findMax Tip = error "
Map.findMax: empty tree has no maximal element"
-- | /O(log n)/. Delete the minimal key
deleteMin :: Map k a -> Map k a
deleteMin (Bin _ kx x Tip r) = r
deleteMin (Bin _ kx x l r) = balance kx x (deleteMin l) r
-- | /O(log n)/. Delete the maximal key
deleteMax :: Map k a -> Map k a
deleteMax (Bin _ kx x l Tip) = l
deleteMax (Bin _ kx x l r) = balance kx x l (deleteMax r)
-- | /O(log n)/. Update the minimal key
updateMin :: (a -> Maybe a) -> Map k a -> Map k a
= updateMinWithKey (\k x -> f x) m
-- | /O(log n)/. Update the maximal key
updateMax :: (a -> Maybe a) -> Map k a -> Map k a
= updateMaxWithKey (\k x -> f x) m
-- | /O(log n)/. Update the minimal key
updateMinWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
Bin sx kx x Tip r -> case f kx x of
Just x' -> Bin sx kx x' Tip r
Bin sx kx x l r -> balance kx x (updateMinWithKey f l) r
-- | /O(log n)/. Update the maximal key
updateMaxWithKey :: (k -> a -> Maybe a) -> Map k a -> Map k a
Bin sx kx x l Tip -> case f kx x of
Just x' -> Bin sx kx x' l Tip
Bin sx kx x l r -> balance kx x l (updateMaxWithKey f r)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | The union of a list of maps: (@unions == foldl union empty@).
unions :: Ord k => [Map k a] -> Map k a
= foldlStrict union empty ts
-- The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
-- It prefers @t1@ when duplicate keys are encountered, ie. (@union == unionWith const@).
-- The implementation uses the efficient /hedge-union/ algorithm.
union :: Ord k => Map k a -> Map k a -> Map k a
union t1 t2 -- hedge-union is more efficient on (bigset `union` smallset)
| size t1 >= size t2 = hedgeUnionL (const LT) (const GT) t1 t2
| otherwise = hedgeUnionR (const LT) (const GT) t2 t1
-- left-biased hedge union
hedgeUnionL cmplo cmphi t1 Tip
hedgeUnionL cmplo cmphi Tip (Bin _ kx x l r)
= join kx x (filterGt cmplo l) (filterLt cmphi r)
hedgeUnionL cmplo cmphi (Bin _ kx x l r) t2
= join kx x (hedgeUnionL cmplo cmpkx l (trim cmplo cmpkx t2))
(hedgeUnionL cmpkx cmphi r (trim cmpkx cmphi t2))
-- right-biased hedge union
hedgeUnionR cmplo cmphi t1 Tip
hedgeUnionR cmplo cmphi Tip (Bin _ kx x l r)
= join kx x (filterGt cmplo l) (filterLt cmphi r)
hedgeUnionR cmplo cmphi (Bin _ kx x l r) t2
= join kx newx (hedgeUnionR cmplo cmpkx l lt)
(hedgeUnionR cmpkx cmphi r gt)
(found,gt) = trimLookupLo kx cmphi t2
{--------------------------------------------------------------------
Union with a combining function
--------------------------------------------------------------------}
-- | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
= unionWithKey (\k x y -> f x y) m1 m2
-- Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
unionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWithKey f Tip t2 = t2
unionWithKey f t1 Tip = t1
unionWithKey f t1 t2 -- hedge-union is more efficient on (bigset `union` smallset)
| size t1 >= size t2 = hedgeUnionWithKey f (const LT) (const GT) t1 t2
| otherwise = hedgeUnionWithKey flipf (const LT) (const GT) t2 t1
hedgeUnionWithKey f cmplo cmphi t1 Tip
hedgeUnionWithKey f cmplo cmphi Tip (Bin _ kx x l r)
= join kx x (filterGt cmplo l) (filterLt cmphi r)
hedgeUnionWithKey f cmplo cmphi (Bin _ kx x l r) t2
= join kx newx (hedgeUnionWithKey f cmplo cmpkx l lt)
(hedgeUnionWithKey f cmpkx cmphi r gt)
(found,gt) = trimLookupLo kx cmphi t2
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(n+m)/. Difference of two maps.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
difference :: Ord k => Map k a -> Map k a -> Map k a
difference t1 t2 = hedgeDiff (const LT) (const GT) t1 t2
hedgeDiff cmplo cmphi Tip t
hedgeDiff cmplo cmphi (Bin _ kx x l r) Tip
= join kx x (filterGt cmplo l) (filterLt cmphi r)
hedgeDiff cmplo cmphi t (Bin _ kx x l r)
= merge (hedgeDiff cmplo cmpkx (trim cmplo cmpkx t) l)
(hedgeDiff cmpkx cmphi (trim cmpkx cmphi t) r)
-- | /O(n+m)/. Difference with a combining function.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
differenceWith :: Ord k => (a -> a -> Maybe a) -> Map k a -> Map k a -> Map k a
= differenceWithKey (\k x y -> f x y) m1 m2
-- | /O(n+m)/. Difference with a combining function. When two equal keys are
-- encountered, the combining function is applied to the key and both values.
-- If it returns @Nothing@, the element is discarded (proper set difference). If
-- it returns (@Just y@), the element is updated with a new value @y@.
-- The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
differenceWithKey :: Ord k => (k -> a -> a -> Maybe a) -> Map k a -> Map k a -> Map k a
differenceWithKey f Tip t2 = Tip
differenceWithKey f t1 Tip = t1
differenceWithKey f t1 t2 = hedgeDiffWithKey f (const LT) (const GT) t1 t2
hedgeDiffWithKey f cmplo cmphi Tip t
hedgeDiffWithKey f cmplo cmphi (Bin _ kx x l r) Tip
= join kx x (filterGt cmplo l) (filterLt cmphi r)
hedgeDiffWithKey f cmplo cmphi t (Bin _ kx x l r)
Just y -> case f kx y x of
Just z -> join kx z tl tr
(found,gt) = trimLookupLo kx cmphi t
tl = hedgeDiffWithKey f cmplo cmpkx lt l
tr = hedgeDiffWithKey f cmpkx cmphi gt r
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(n+m)/. Intersection of two maps. The values in the first
-- map are returned,
i.e. (@intersection m1 m2 == intersectionWith const m1 m2@).
intersection :: Ord k => Map k a -> Map k a -> Map k a
= intersectionWithKey (\k x y -> x) m1 m2
-- | /O(n+m)/. Intersection with a combining function.
intersectionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
= intersectionWithKey (\k x y -> f x y) m1 m2
-- | /O(n+m)/. Intersection with a combining function.
intersectionWithKey :: Ord k => (k -> a -> a -> a) -> Map k a -> Map k a -> Map k a
intersectionWithKey f Tip t = Tip
intersectionWithKey f t Tip = Tip
intersectionWithKey f t1 t2 -- intersection is more efficient on (bigset `intersection` smallset)
| size t1 >= size t2 = intersectWithKey f t1 t2
| otherwise = intersectWithKey flipf t2 t1
intersectWithKey f Tip t = Tip
intersectWithKey f t Tip = Tip
intersectWithKey f t (Bin _ kx x l r)
Just y -> join kx (f kx y x) tl tr
(found,lt,gt) = splitLookup kx t
tl = intersectWithKey f lt l
tr = intersectWithKey f gt r
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- This function is defined as (@subset = subsetBy (==)@).
subset :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
The expression (@subsetBy f t1 t2@) returns @True@ if
all keys in @t1@ are in tree @t2@, and when @f@ returns @True@ when
applied to their respective values. For example, the following
expressions are all @True@.
> subsetBy (==) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
> subsetBy (<=) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
> subsetBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1),('b',2)])
But the following are all @False@:
> subsetBy (==) (fromList [('a',2)]) (fromList [('a',1),('b',2)])
> subsetBy (<) (fromList [('a',1)]) (fromList [('a',1),('b',2)])
> subsetBy (==) (fromList [('a',1),('b',2)]) (fromList [('a',1)])
subsetBy :: Ord k => (a->a->Bool) -> Map k a -> Map k a -> Bool
= (size t1 <= size t2) && (subset' f t1 t2)
subset' f (Bin _ kx x l r) t
Just y -> f x y && subset' f l lt && subset' f r gt
(found,lt,gt) = splitLookup kx t
-- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
-- Defined as (@properSubset = properSubsetBy (==)@).
properSubset :: (Ord k,Eq a) => Map k a -> Map k a -> Bool
= properSubsetBy (==) m1 m2
{- | /O(n+m)/. Is this a proper subset? (ie. a subset but not equal).
The expression (@properSubsetBy f m1 m2@) returns @True@ when
@m1@ and @m2@ are not equal,
all keys in @m1@ are in @m2@, and when @f@ returns @True@ when
applied to their respective values. For example, the following
expressions are all @True@.
> properSubsetBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
> properSubsetBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
But the following are all @False@:
> properSubsetBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
> properSubsetBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
> properSubsetBy (<) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
properSubsetBy :: (Ord k,Eq a) => (a -> a -> Bool) -> Map k a -> Map k a -> Bool
= (size t1 < size t2) && (subset' f t1 t2)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(n)/. Filter all values that satisfy the predicate.
filter :: Ord k => (a -> Bool) -> Map k a -> Map k a
= filterWithKey (\k x -> p x) m
-- | /O(n)/. Filter all keys\values that satisfy the predicate.
filterWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> Map k a
filterWithKey p Tip = Tip
filterWithKey p (Bin _ kx x l r)
| p kx x = join kx x (filterWithKey p l) (filterWithKey p r)
| otherwise = merge (filterWithKey p l) (filterWithKey p r)
-- | /O(n)/. partition the map according to a predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
partition :: Ord k => (a -> Bool) -> Map k a -> (Map k a,Map k a)
= partitionWithKey (\k x -> p x) m
-- | /O(n)/. partition the map according to a predicate. The first
-- map contains all elements that satisfy the predicate, the second all
-- elements that fail the predicate. See also 'split'.
partitionWithKey :: Ord k => (k -> a -> Bool) -> Map k a -> (Map k a,Map k a)
partitionWithKey p Tip = (Tip,Tip)
partitionWithKey p (Bin _ kx x l r)
| p kx x = (join kx x l1 r1,merge l2 r2)
| otherwise = (merge l1 r1,join kx x l2 r2)
(l1,l2) = partitionWithKey p l
(r1,r2) = partitionWithKey p r
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(n)/. Map a function over all values in the map.
map :: (a -> b) -> Map k a -> Map k b
= mapWithKey (\k x -> f x) m
-- | /O(n)/. Map a function over all values in the map.
mapWithKey :: (k -> a -> b) -> Map k a -> Map k b
mapWithKey f (Bin sx kx x l r)
= Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)
-- | /O(n)/. The function @mapAccum@ threads an accumulating
-- argument through the map in an unspecified order.
mapAccum :: (a -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
= mapAccumWithKey (\a k x -> f a x) a m
-- | /O(n)/. The function @mapAccumWithKey@ threads an accumulating
-- argument through the map in unspecified order. (= ascending pre-order)
mapAccumWithKey :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
-- | /O(n)/. The function @mapAccumL@ threads an accumulating
-- argument throught the map in (ascending) pre-order.
mapAccumL :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
-> let (a1,l') = mapAccumL f a l
(a3,r') = mapAccumL f a2 r
in (a3,Bin sx kx x' l' r')
-- | /O(n)/. The function @mapAccumR@ threads an accumulating
-- argument throught the map in (descending) post-order.
mapAccumR :: (a -> k -> b -> (a,c)) -> a -> Map k b -> (a,Map k c)
-> let (a1,r') = mapAccumR f a r
(a3,l') = mapAccumR f a2 l
in (a3,Bin sx kx x' l' r')
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(n)/. Fold the map in an unspecified order. (= descending post-order).
fold :: (a -> b -> b) -> b -> Map k a -> b
= foldWithKey (\k x z -> f x z) z m
-- | /O(n)/. Fold the map in an unspecified order. (= descending post-order).
foldWithKey :: (k -> a -> b -> b) -> b -> Map k a -> b
-- | /O(n)/. In-order fold.
foldI :: (k -> a -> b -> b -> b) -> b -> Map k a -> b
foldI f z (Bin _ kx x l r) = f kx x (foldI f z l) (foldI f z r)
-- | /O(n)/. Post-order fold.
foldR :: (k -> a -> b -> b) -> b -> Map k a -> b
foldR f z (Bin _ kx x l r) = foldR f (f kx x (foldR f z r)) l
-- | /O(n)/. Pre-order fold.
foldL :: (b -> k -> a -> b) -> b -> Map k a -> b
foldL f z (Bin _ kx x l r) = foldL f (f (foldL f z l) kx x) r
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(n)/. Return all elements of the map.
= [x | (k,x) <- assocs m]
-- | /O(n)/. Return all keys of the map.
= [k | (k,x) <- assocs m]
-- | /O(n)/. Return all key\/value pairs in the map.
assocs :: Map k a -> [(k,a)]
{--------------------------------------------------------------------
use [foldlStrict] to reduce demand on the control-stack
--------------------------------------------------------------------}
-- | /O(n*log n)/. Build a map from a list of key\/value pairs. See also 'fromAscList'.
fromList :: Ord k => [(k,a)] -> Map k a
= foldlStrict ins empty xs
ins t (k,x) = insert k x t
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWith'.
fromListWith :: Ord k => (a -> a -> a) -> [(k,a)] -> Map k a
= fromListWithKey (\k x y -> f x y) xs
-- | /O(n*log n)/. Build a map from a list of key\/value pairs with a combining function. See also 'fromAscListWithKey'.
fromListWithKey :: Ord k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
= foldlStrict ins empty xs
ins t (k,x) = insertWithKey f k x t
-- | /O(n)/. Convert to a list of key\/value pairs.
toList :: Map k a -> [(k,a)]
-- | /O(n)/. Convert to an ascending list.
toAscList :: Map k a -> [(k,a)]
toAscList t = foldR (\k x xs -> (k,x):xs) [] t
toDescList :: Map k a -> [(k,a)]
toDescList t = foldL (\xs k x -> (k,x):xs) [] t
{--------------------------------------------------------------------
Note that if [xs] is ascending that:
fromAscList xs == fromList xs
fromAscListWith f xs == fromListWith f xs
--------------------------------------------------------------------}
-- | /O(n)/. Build a map from an ascending list in linear time.
fromAscList :: Eq k => [(k,a)] -> Map k a
= fromAscListWithKey (\k x y -> x) xs
-- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys.
fromAscListWith :: Eq k => (a -> a -> a) -> [(k,a)] -> Map k a
= fromAscListWithKey (\k x y -> f x y) xs
-- | /O(n)/. Build a map from an ascending list in linear time with a combining function for equal keys
fromAscListWithKey :: Eq k => (k -> a -> a -> a) -> [(k,a)] -> Map k a
= fromDistinctAscList (combineEq f xs)
-- [combineEq f xs] combines equal elements with function [f] in an ordered list [xs]
(x:xx) -> combineEq' x xx
combineEq' z@(kz,zz) (x@(kx,xx):xs)
| kx==kz = let yy = f kx xx zz in combineEq' (kx,yy) xs
| otherwise = z:combineEq' x xs
-- | /O(n)/. Build a map from an ascending list of distinct elements in linear time.
fromDistinctAscList :: [(k,a)] -> Map k a
= build const (length xs) xs
-- 1) use continutations so that we use heap space instead of stack space.
-- 2) special case for n==5 to build bushier trees.
build c 5 xs = case xs of
((k1,x1):(k2,x2):(k3,x3):(k4,x4):(k5,x5):xx)
-> c (bin k4 x4 (bin k2 x2 (single k1 x1) (single k3 x3)) (single k5 x5)) xx
build c n xs = seq nr $ build (buildR nr c) nl xs
buildR n c l ((k,x):ys) = build (buildB l k x c) n ys
buildB l k x c r zs = c (bin k x l r) zs
{--------------------------------------------------------------------
Utility functions that return sub-ranges of the original
tree. Some functions take a comparison function as argument to
allow comparisons against infinite values. A function [cmplo k]
should be read as [compare lo k].
[trim cmplo cmphi t] A tree that is either empty or where [cmplo k == LT]
and [cmphi k == GT] for the key [k] of the root.
[filterGt cmp t] A tree where for all keys [k]. [cmp k == LT]
[filterLt cmp t] A tree where for all keys [k]. [cmp k == GT]
[split k t] Returns two trees [l] and [r] where all keys
in [l] are <[k] and all keys in [r] are >[k].
[splitLookup k t] Just like [split] but also returns whether [k]
--------------------------------------------------------------------}
{--------------------------------------------------------------------
[trim lo hi t] trims away all subtrees that surely contain no
values between the range [lo] to [hi]. The returned tree is either
empty or the key of the root is between @lo@ and @hi@.
--------------------------------------------------------------------}
trim :: (k -> Ordering) -> (k -> Ordering) -> Map k a -> Map k a
trim cmplo cmphi Tip = Tip
trim cmplo cmphi t@(Bin sx kx x l r)
trimLookupLo :: Ord k => k -> (k -> Ordering) -> Map k a -> (Maybe a, Map k a)
trimLookupLo lo cmphi Tip = (Nothing,Tip)
trimLookupLo lo cmphi t@(Bin sx kx x l r)
le -> trimLookupLo lo cmphi l
GT -> trimLookupLo lo cmphi r
EQ -> (Just x,trim (compare lo) cmphi r)
{--------------------------------------------------------------------
[filterGt k t] filter all keys >[k] from tree [t]
[filterLt k t] filter all keys <[k] from tree [t]
--------------------------------------------------------------------}
filterGt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
filterGt cmp (Bin sx kx x l r)
LT -> join kx x (filterGt cmp l) r
filterLt :: Ord k => (k -> Ordering) -> Map k a -> Map k a
filterLt cmp (Bin sx kx x l r)
GT -> join kx x l (filterLt cmp r)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(log n)/. The expression (@split k map@) is a pair @(map1,map2)@ where
-- the keys in @map1@ are smaller than @k@ and the keys in @map2@ larger than @k@.
split :: Ord k => k -> Map k a -> (Map k a,Map k a)
split k (Bin sx kx x l r)
LT -> let (lt,gt) = split k l in (lt,join kx x gt r)
GT -> let (lt,gt) = split k r in (join kx x l lt,gt)
-- | /O(log n)/. The expression (@splitLookup k map@) splits a map just
-- like 'split' but also returns @lookup k map@.
splitLookup :: Ord k => k -> Map k a -> (Maybe a,Map k a,Map k a)
splitLookup k Tip = (Nothing,Tip,Tip)
splitLookup k (Bin sx kx x l r)
LT -> let (z,lt,gt) = splitLookup k l in (z,lt,join kx x gt r)
GT -> let (z,lt,gt) = splitLookup k r in (z,join kx x l lt,gt)
{--------------------------------------------------------------------
Utility functions that maintain the balance properties of the tree.
All constructors assume that all values in [l] < [k] and all values
in [r] > [k], and that [l] and [r] are valid trees.
In order of sophistication:
[Bin sz k x l r] The type constructor.
[bin k x l r] Maintains the correct size, assumes that both [l]
and [r] are balanced with respect to each other.
[balance k x l r] Restores the balance and size.
Assumes that the original tree was balanced and
that [l] or [r] has changed by at most one element.
[join k x l r] Restores balance and size.
Furthermore, we can construct a new tree from two trees. Both operations
assume that all values in [l] < all values in [r] and that [l] and [r]
[glue l r] Glues [l] and [r] together. Assumes that [l] and
[r] are already balanced with respect to each other.
[merge l r] Merges two trees and restores balance.
Note: in contrast to Adam's paper, we use (<=) comparisons instead
of (<) comparisons in [join], [merge] and [balance].
Quickcheck (on [difference]) showed that this was necessary in order
to maintain the invariants. It is quite unsatisfactory that I haven't
been able to find out why this is actually the case! Fortunately, it
doesn't hurt to be a bit more conservative.
--------------------------------------------------------------------}
{--------------------------------------------------------------------
--------------------------------------------------------------------}
join :: Ord k => k -> a -> Map k a -> Map k a -> Map k a
join kx x Tip r = insertMin kx x r
join kx x l Tip = insertMax kx x l
join kx x l@(Bin sizeL ky y ly ry) r@(Bin sizeR kz z lz rz)
| delta*sizeL <= sizeR = balance kz z (join kx x l lz) rz
| delta*sizeR <= sizeL = balance ky y ly (join kx x ry r)
| otherwise = bin kx x l r
-- insertMin and insertMax don't perform potentially expensive comparisons.
insertMax,insertMin :: k -> a -> Map k a -> Map k a
-> balance ky y l (insertMax kx x r)
-> balance ky y (insertMin kx x l) r
{--------------------------------------------------------------------
[merge l r]: merges two trees.
--------------------------------------------------------------------}
merge :: Map k a -> Map k a -> Map k a
merge l@(Bin sizeL kx x lx rx) r@(Bin sizeR ky y ly ry)
| delta*sizeL <= sizeR = balance ky y (merge l ly) ry
| delta*sizeR <= sizeL = balance kx x lx (merge rx r)
{--------------------------------------------------------------------
[glue l r]: glues two trees together.
Assumes that [l] and [r] are already balanced with respect to each other.
--------------------------------------------------------------------}
glue :: Map k a -> Map k a -> Map k a
| size l > size r = let ((km,m),l') = deleteFindMax l in balance km m l' r
| otherwise = let ((km,m),r') = deleteFindMin r in balance km m l r'
-- | /O(log n)/. Delete and find the minimal element.
deleteFindMin :: Map k a -> ((k,a),Map k a)
Bin _ k x Tip r -> ((k,x),r)
Bin _ k x l r -> let (km,l') = deleteFindMin l in (km,balance k x l' r)
Tip -> (error "
Map.deleteFindMin: can not return the minimal element of an empty map", Tip)
-- | /O(log n)/. Delete and find the maximal element.
deleteFindMax :: Map k a -> ((k,a),Map k a)
Bin _ k x l Tip -> ((k,x),l)
Bin _ k x l r -> let (km,r') = deleteFindMax r in (km,balance k x l r')
Tip -> (error "
Map.deleteFindMax: can not return the maximal element of an empty map", Tip)
{--------------------------------------------------------------------
[balance l x r] balances two trees with value x.
The sizes of the trees should balance after decreasing the
size of one of them. (a rotation).
[delta] is the maximal relative difference between the sizes of
two trees, it corresponds with the [w] in Adams' paper.
[ratio] is the ratio between an outer and inner sibling of the
heavier subtree in an unbalanced setting. It determines
whether a double or single rotation should be performed
to restore balance. It is correspondes with the inverse
of $\alpha$ in Adam's article.
- [delta] should be larger than 4.646 with a [ratio] of 2.
- [delta] should be larger than 3.745 with a [ratio] of 1.534.
- A lower [delta] leads to a more 'perfectly' balanced tree.
- A higher [delta] performs less rebalancing.
- Balancing is automaic for random data and a balancing
scheme is only necessary to avoid pathological worst cases.
Almost any choice will do, and in practice, a rather large
[delta] may perform better than smaller one.
Note: in contrast to Adam's paper, we use a ratio of (at least) [2]
to decide whether a single or double rotation is needed. Allthough
he actually proves that this ratio is needed to maintain the
invariants, his implementation uses an invalid ratio of [1].
--------------------------------------------------------------------}
balance :: k -> a -> Map k a -> Map k a -> Map k a
| sizeL + sizeR <= 1 = Bin sizeX k x l r
| sizeR >= delta*sizeL = rotateL k x l r
| sizeL >= delta*sizeR = rotateR k x l r
| otherwise = Bin sizeX k x l r
sizeX = sizeL + sizeR + 1
rotateL k x l r@(Bin _ _ _ ly ry)
| size ly < ratio*size ry = singleL k x l r
| otherwise = doubleL k x l r
rotateR k x l@(Bin _ _ _ ly ry) r
| size ry < ratio*size ly = singleR k x l r
| otherwise = doubleR k x l r
singleL k1 x1 t1 (Bin _ k2 x2 t2 t3) = bin k2 x2 (bin k1 x1 t1 t2) t3
singleR k1 x1 (Bin _ k2 x2 t1 t2) t3 = bin k2 x2 t1 (bin k1 x1 t2 t3)
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)
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)
{--------------------------------------------------------------------
The bin constructor maintains the size of the tree
--------------------------------------------------------------------}
bin :: k -> a -> Map k a -> Map k a -> Map k a
= Bin (size l + size r + 1) k x l r
{--------------------------------------------------------------------
Eq converts the tree to a list. In a lazy setting, this
actually seems one of the faster methods to compare two trees
and it is certainly the simplest :-)
--------------------------------------------------------------------}
instance (Eq k,Eq a) => Eq (Map k a) where
t1 == t2 = (size t1 == size t2) && (toAscList t1 == toAscList t2)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
instance Functor (Map k) where
{--------------------------------------------------------------------
--------------------------------------------------------------------}
instance (Show k, Show a) => Show (Map k a) where
showsPrec d m = showMap (toAscList m)
showMap :: (Show k,Show a) => [(k,a)] -> ShowS
= showChar '{' . showElem x . showTail xs
showTail [] = showChar '}'
showTail (x:xs) = showChar ',' . showElem x . showTail xs
showElem (k,x) = shows k . showString ":=" . shows x
-- | /O(n)/. Show the tree that implements the map. The tree is shown
-- in a compressed, hanging format.
showTree :: (Show k,Show a) => Map k a -> String
= showTreeWith showElem True False m
showElem k x = show k ++ ":=" ++ show x
{- | /O(n)/. The expression (@showTreeWith showelem hang wide map@) shows
the tree that implements the map. Elements are shown using the @showElem@ function. If @hang@ is
@True@, a /hanging/ tree is shown otherwise a rotated tree is shown. If
@wide@ is true, an extra wide version is shown.
> Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True False $ fromDistinctAscList [(x,()) | x <- [1..5]]
> Map> putStrLn $ showTreeWith (\k x -> show (k,x)) True True $ fromDistinctAscList [(x,()) | x <- [1..5]]
> Map> putStrLn $ showTreeWith (\k x -> show (k,x)) False True $ fromDistinctAscList [(x,()) | x <- [1..5]]
showTreeWith :: (k -> a -> String) -> Bool -> Bool -> Map k a -> String
showTreeWith showelem hang wide t
| hang = (showsTreeHang showelem wide [] t) ""
| otherwise = (showsTree showelem wide [] [] t) ""
showsTree :: (k -> a -> String) -> Bool -> [String] -> [String] -> Map k a -> ShowS
showsTree showelem wide lbars rbars t
Tip -> showsBars lbars . showString "|\n"
-> showsBars lbars . showString (showelem kx x) . showString "\n"
-> showsTree showelem wide (withBar rbars) (withEmpty rbars) r .
showsBars lbars . showString (showelem kx x) . showString "\n" .
showsTree showelem wide (withEmpty lbars) (withBar lbars) l
showsTreeHang :: (k -> a -> String) -> Bool -> [String] -> Map k a -> ShowS
showsTreeHang showelem wide bars t
Tip -> showsBars bars . showString "|\n"
-> showsBars bars . showString (showelem kx x) . showString "\n"
-> showsBars bars . showString (showelem kx x) . showString "\n" .
showsTreeHang showelem wide (withBar bars) l .
showsTreeHang showelem wide (withEmpty bars) r
| wide = showString (concat (reverse bars)) . showString "|\n"
showsBars :: [String] -> ShowS
_ -> showString (concat (reverse (tail bars))) . showString node
withEmpty bars = " ":bars
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- | /O(n)/. Test if the internal map structure is valid.
valid :: Ord k => Map k a -> Bool
= balanced t && ordered t && validsize t
= bounded (const True) (const True) t
Bin sz kx x l r -> (lo kx) && (hi kx) && bounded lo (<kx) l && bounded (>kx) hi r
balanced :: Map k a -> Bool
Bin sz kx x l r -> (size l + size r <= 1 || (size l <= delta*size r && size r <= delta*size l)) &&
= (realsize t == Just (size t))
Bin sz kx x l r -> case (realsize l,realsize r) of
(Just n,Just m) | n+m+1 == sz -> Just sz
{--------------------------------------------------------------------
--------------------------------------------------------------------}
(x:xx) -> let z' = f z x in seq z' (foldlStrict f z' xx)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
testTree xs = fromList [(x,"*") | x <- xs]
test2 = testTree [30,29..10]
test3 = testTree [1,4,6,89,2323,53,43,234,5,79,12,9,24,9,8,423,8,42,4,8,9,3]
{--------------------------------------------------------------------
--------------------------------------------------------------------}
, configSize = \n -> (div n 2 + 3)
, configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ]
{--------------------------------------------------------------------
Arbitrary, reasonably balanced trees
--------------------------------------------------------------------}
instance (Enum k,Arbitrary a) => Arbitrary (Map k a) where
arbitrary = sized (arbtree 0 maxkey)
arbtree :: (Enum k,Arbitrary a) => Int -> Int -> Int -> Gen (Map k a)
| otherwise = do{ x <- arbitrary
; let (ml,mr) | m==(1::Int)= (1,2)
; l <- arbtree lo (i-1) (n `div` ml)
; r <- arbtree (i+1) hi (n `div` mr)
; return (bin (toEnum i) x l r)
{--------------------------------------------------------------------
--------------------------------------------------------------------}
forValid :: (Show k,Enum k,Show a,Arbitrary a,Testable b) => (Map k a -> b) -> Property
= forAll arbitrary $ \t ->
-- classify (balanced t) "balanced" $
classify (size t == 0) "empty" $
classify (size t > 0 && size t <= 10) "small" $
classify (size t > 10 && size t <= 64) "medium" $
classify (size t > 64) "large" $
forValidIntTree :: Testable a => (Map Int Int -> a) -> Property
forValidUnitTree :: Testable a => (Map Int () -> a) -> Property
= forValidUnitTree $ \t -> valid t
{--------------------------------------------------------------------
--------------------------------------------------------------------}
prop_Single :: Int -> Int -> Bool
= (insert k x empty == single k x)
prop_InsertValid :: Int -> Property
= forValidUnitTree $ \t -> valid (insert k () t)
prop_InsertDelete :: Int -> Map Int () -> Property
= (lookup k t == Nothing) ==> delete k (insert k () t) == t
prop_DeleteValid :: Int -> Property
= forValidUnitTree $ \t ->
valid (delete k (insert k () t))
{--------------------------------------------------------------------
--------------------------------------------------------------------}
prop_Join :: Int -> Property
= forValidUnitTree $ \t ->
prop_Merge :: Int -> Property
= forValidUnitTree $ \t ->
{--------------------------------------------------------------------
--------------------------------------------------------------------}
prop_UnionValid :: Property
= forValidUnitTree $ \t1 ->
forValidUnitTree $ \t2 ->
prop_UnionInsert :: Int -> Int -> Map Int Int -> Bool
= union (single k x) t == insert k x t
prop_UnionAssoc :: Map Int Int -> Map Int Int -> Map Int Int -> Bool
= union t1 (union t2 t3) == union (union t1 t2) t3
prop_UnionComm :: Map Int Int -> Map Int Int -> Bool
= (union t1 t2 == unionWith (\x y -> y) t2 t1)
= forValidIntTree $ \t1 ->
valid (unionWithKey (\k x y -> x+y) t1 t2)
prop_UnionWith :: [(Int,Int)] -> [(Int,Int)] -> Bool
= sum (elems (unionWith (+) (fromListWith (+) xs) (fromListWith (+) ys)))
= forValidUnitTree $ \t1 ->
forValidUnitTree $ \t2 ->
prop_Diff :: [(Int,Int)] -> [(Int,Int)] -> Bool
=
List.sort (keys (difference (fromListWith (+) xs) (fromListWith (+) ys)))
= forValidUnitTree $ \t1 ->
forValidUnitTree $ \t2 ->
valid (intersection t1 t2)
prop_Int :: [(Int,Int)] -> [(Int,Int)] -> Bool
=
List.sort (keys (intersection (fromListWith (+) xs) (fromListWith (+) ys)))
{--------------------------------------------------------------------
--------------------------------------------------------------------}
= forAll (choose (5,100)) $ \n ->
let xs = [(x,()) | x <- [
0..n::Int]]
in fromAscList xs == fromList xs
prop_List :: [Int] -> Bool
= (sort (nub xs) == [x | (x,()) <- toList (fromList [(x,()) | x <- xs])])