import Prelude hiding (lookup,map,filter,foldr,foldl,null)
import Data.Bits
import Data.Int
-import Data.Monoid
import qualified Data.IntSet as IntSet
import Data.Typeable
{--------------------------------------------------------------------
Insert
- 'insert' is the inlined version of 'insertWith (\k x y -> x)'
--------------------------------------------------------------------}
--- | /O(min(n,W))/. Insert a new key\/value pair in the map. When the key
--- is already an element of the set, its value is replaced by the new value,
--- ie. 'insert' is left-biased.
+-- | /O(min(n,W))/. Insert a new key\/value pair in the map.
+-- If the key is already present in the map, the associated value is
+-- replaced with the supplied value, i.e. 'insert' is equivalent to
+-- @'insertWith' 'const'@.
insert :: Key -> a -> IntMap a -> IntMap a
insert k x t
= case t of
unionsWith f ts
= foldlStrict (unionWith f) empty ts
--- | /O(n+m)/. The (left-biased) union of two sets.
+-- | /O(n+m)/. The (left-biased) union of two maps.
+-- It prefers the first map when duplicate keys are encountered,
+-- i.e. (@'union' == 'unionWith' 'const'@).
union :: IntMap a -> IntMap a -> IntMap a
union t1@(Bin p1 m1 l1 r1) t2@(Bin p2 m2 l2 r2)
| shorter m1 m2 = union1
split k t
= case t of
Bin p m l r
+ | nomatch k p m -> if k>p then (t,Nil) else (Nil,t)
| zero k m -> let (lt,gt) = split k l in (lt,union gt r)
| otherwise -> let (lt,gt) = split k r in (union l lt,gt)
Tip ky y
-- | /O(log n)/. Performs a 'split' but also returns whether the pivot
-- key was found in the original map.
-splitLookup :: Key -> IntMap a -> (Maybe a,IntMap a,IntMap a)
+splitLookup :: Key -> IntMap a -> (IntMap a,Maybe a,IntMap a)
splitLookup k t
= case t of
Bin p m l r
- | zero k m -> let (found,lt,gt) = splitLookup k l in (found,lt,union gt r)
- | otherwise -> let (found,lt,gt) = splitLookup k r in (found,union l lt,gt)
+ | nomatch k p m -> if k>p then (t,Nothing,Nil) else (Nil,Nothing,t)
+ | zero k m -> let (lt,found,gt) = splitLookup k l in (lt,found,union gt r)
+ | otherwise -> let (lt,found,gt) = splitLookup k r in (union l lt,found,gt)
Tip ky y
- | k>ky -> (Nothing,t,Nil)
- | k<ky -> (Nothing,Nil,t)
- | otherwise -> (Just y,Nil,Nil)
- Nil -> (Nothing,Nil,Nil)
+ | k>ky -> (t,Nothing,Nil)
+ | k<ky -> (Nil,Nothing,t)
+ | otherwise -> (Nil,Just y,Nil)
+ Nil -> (Nil,Nothing,Nil)
{--------------------------------------------------------------------
Fold
fmap = map
{--------------------------------------------------------------------
- Monoid
---------------------------------------------------------------------}
-
-instance Ord a => Monoid (IntMap a) where
- mempty = empty
- mappend = union
- mconcat = unions
-
-{--------------------------------------------------------------------
Show
--------------------------------------------------------------------}