Map.icl 86.2 KB
Newer Older
1
implementation module Data.Map
2

3
import StdEnv
Mart Lubbers's avatar
Mart Lubbers committed
4 5 6 7 8 9 10
import Data.Either
import Data.GenLexOrd
import Data.Maybe
import Data.Monoid
import Data.Functor
import Data.List
import Control.Applicative
11 12
import Control.Monad

Mart Lubbers's avatar
Mart Lubbers committed
13
import qualified Data.Set
Mart Lubbers's avatar
Mart Lubbers committed
14
from Data.Set import :: Set
Mart Lubbers's avatar
Mart Lubbers committed
15

16 17
// Ported from Haskell`s Data.Map by Jurriën Stutterheim, 10-09-2014

18
instance Semigroup (Map k v) | < k where
19 20
    mappend x y = union x y

21 22 23
instance Monoid (Map k v) | < k where
    mempty = newMap

24 25 26
mapSize :: !(Map k a) -> Int
mapSize Tip              = 0
mapSize (Bin sz _ _ _ _) = sz
27

28
lexOrd x y :== if (x < y) LT (if (x > y) GT EQ)
29

30 31
member :: !k !(Map k a) -> Bool | < k
member _ Tip              = False
32 33 34 35 36
member k (Bin _ kx _ l r) = if (k < kx)
                              (member k l)
                              (if (k > kx)
                                 (member k r)
                                 True)
37

38 39
find :: !k !(Map k a) -> a | < k
find _ Tip              = abort "Map.!: given key is not an element in the map"
40 41 42 43 44
find k (Bin _ kx x l r) = if (k < kx)
                              (find k l)
                              (if (k > kx)
                                 (find k r)
                                 x)
45

46 47
findWithDefault :: !a !k !(Map k a) -> a | < k
findWithDefault def _ Tip              = def
48 49 50 51 52
findWithDefault def k (Bin _ kx x l r) = if (k < kx)
                                           (findWithDefault def k l)
                                           (if (k > kx)
                                              (findWithDefault def k r)
                                              x)
53

54
findKey :: !a !(Map k a) -> Maybe k | == a
Peter Achten's avatar
Peter Achten committed
55
findKey a m = findKeyWith ((==) a) m
56

Peter Achten's avatar
Peter Achten committed
57 58
findKeyWith :: !(a -> Bool) !(Map k a) -> Maybe k
findKeyWith select m = listToMaybe [k` \\ (k`,v) <- toList m | select v]
59 60

findKeyWithDefault :: !k !a !(Map k a) -> k | == a
Peter Achten's avatar
Peter Achten committed
61
findKeyWithDefault k a m = findKeyWithDefaultWith ((==) a) k m
62

Peter Achten's avatar
Peter Achten committed
63 64
findKeyWithDefaultWith :: !(a -> Bool) !k !(Map k a) -> k
findKeyWithDefaultWith compare k m = fromMaybe k (findKeyWith compare m)
65

66 67 68 69 70
// | /O(log n)/. Find largest key smaller than the given one and return the
// corresponding (key, value) pair.
//
// > getLT 3 (fromList [(3,'a`), (5,'b`)]) == Nothing
// > getLT 4 (fromList [(3,'a`), (5,'b`)]) == Just (3, 'a`)
71
getLT :: !k !(Map k v) -> Maybe (!k, !v) | < k
72 73
getLT k m = goNothing k m
  where
74 75 76 77 78 79 80 81 82 83 84
  goNothing :: !k !(Map k v) -> Maybe (!k, !v) | < k
  goNothing _ Tip = Nothing
  goNothing k (Bin _ kx x l r)
    | k <= kx   = goNothing k l
    | otherwise = goJust k kx x r

  goJust :: !k !k !v !(Map k v) -> Maybe (!k, !v) | < k
  goJust _ kx` x` Tip = Just (kx`, x`)
  goJust k kx` x` (Bin _ kx x l r)
    | k <= kx   = goJust k kx` x` l
    | otherwise = goJust k kx x r
85 86 87 88 89 90

// | /O(log n)/. Find smallest key greater than the given one and return the
// corresponding (key, value) pair.
//
// > getGT 4 (fromList [(3,'a`), (5,'b`)]) == Just (5, 'b`)
// > getGT 5 (fromList [(3,'a`), (5,'b`)]) == Nothing
91
getGT :: !k !(Map k v) -> Maybe (!k, !v) | < k
92 93
getGT k m = goNothing k m
  where
94 95 96 97 98 99 100 101 102 103 104
  goNothing :: !k !(Map k v) -> Maybe (!k, !v) | < k
  goNothing _ Tip = Nothing
  goNothing k (Bin _ kx x l r)
    | k < kx    = goJust k kx x l
    | otherwise = goNothing k r

  goJust :: !k !k !v !(Map k v) -> Maybe (!k, !v) | < k
  goJust _ kx` x` Tip = Just (kx`, x`)
  goJust k kx` x` (Bin _ kx x l r)
    | k < kx    = goJust k kx x l
    | otherwise = goJust k kx` x` r
105 106 107 108 109 110 111

// | /O(log n)/. Find largest key smaller or equal to the given one and return
// the corresponding (key, value) pair.
//
// > getLE 2 (fromList [(3,'a`), (5,'b`)]) == Nothing
// > getLE 4 (fromList [(3,'a`), (5,'b`)]) == Just (3, 'a`)
// > getLE 5 (fromList [(3,'a`), (5,'b`)]) == Just (5, 'b`)
112
getLE :: !k !(Map k v) -> Maybe (!k, !v) | < k
113 114
getLE k m = goNothing k m
  where
115 116
  goNothing :: !k !(Map k v) -> Maybe (!k, !v) | < k
  goNothing _ Tip              = Nothing
117 118 119 120 121
  goNothing k (Bin _ kx x l r) = if (k < kx)
                                   (goNothing k l)
                                   (if (k > kx)
                                      (goJust k kx x r)
                                      (Just (kx, x)))
122 123 124

  goJust :: !k !k !v !(Map k v) -> Maybe (!k, !v) | < k
  goJust _ kx` x` Tip              = Just (kx`, x`)
125 126 127 128 129
  goJust k kx` x` (Bin _ kx x l r) = if (k < kx)
                                       (goJust k kx` x` l)
                                       (if (k > kx)
                                          (goJust k kx x r)
                                          (Just (kx, x)))
130 131 132 133 134 135 136

// | /O(log n)/. Find smallest key greater or equal to the given one and return
// the corresponding (key, value) pair.
//
// > getGE 3 (fromList [(3,'a`), (5,'b`)]) == Just (3, 'a`)
// > getGE 4 (fromList [(3,'a`), (5,'b`)]) == Just (5, 'b`)
// > getGE 6 (fromList [(3,'a`), (5,'b`)]) == Nothing
137
getGE :: !k !(Map k v) -> Maybe (!k, !v) | < k
138 139
getGE k m = goNothing k m
  where
140 141 142 143 144 145 146 147 148 149 150 151 152
  goNothing :: !k !(Map k v) -> Maybe (!k, !v) | < k
  goNothing _ Tip              = Nothing
  goNothing k (Bin _ kx x l r) = case lexOrd k kx of
                                   LT -> goJust k kx x l
                                   EQ -> Just (kx, x)
                                   GT -> goNothing k r

  goJust :: !k !k !v !(Map k v) -> Maybe (!k, !v) | < k
  goJust _ kx` x` Tip              = Just (kx`, x`)
  goJust k kx` x` (Bin _ kx x l r) = case lexOrd k kx of
                                       LT -> goJust k kx x l
                                       EQ -> Just (kx, x)
                                       GT -> goJust k kx` x` r
153

Bas Lijnse's avatar
Bas Lijnse committed
154
newMap :: w:(Map k u:v), [ w <= u]
155 156
newMap = Tip

157
singleton :: !k !a -> Map k a
158 159 160
singleton k x = Bin 1 k x Tip Tip

// See Note: Type of local 'go' function
161
put :: !k !a !(Map k a) -> Map k a | < k
162
put kx x Tip               = singleton kx x
163
put kx x (Bin sz ky y l r) =
164 165 166 167 168
  if (kx < ky)
    (balanceL ky y (put kx x l) r)
    (if (kx > ky)
       (balanceR ky y l (put kx x r))
       (Bin sz kx x l r))
169 170 171 172 173

// Insert a new key and value in the map if it is not already present.
// Used by `union`.

// See Note: Type of local 'go' function
174 175 176
putR :: !k !a !(Map k a) -> Map k a | < k
putR kx x Tip = singleton kx x
putR kx x t=:(Bin _ ky y l r) =
177 178 179 180 181
  if (kx < ky)
    (balanceL ky y (putR kx x l) r)
    (if (kx > ky)
       (balanceR ky y l (putR kx x r))
       t)
182 183 184 185 186 187 188 189 190 191 192

// | /O(log n)/. Insert with a function, combining new value and old value.
// @'putWith' f key value mp@
// will put the pair (key, value) into @mp@ if key does
// not exist in the map. If the key does exist, the function will
// put the pair @(key, f new_value old_value)@.
//
// > putWith (++) 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "xxxa")]
// > putWith (++) 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
// > putWith (++) 5 "xxx" newMap                         == singleton 5 "xxx"

193
putWith :: !(a a -> a) !k !a !(Map k a) -> Map k a | < k
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
putWith f k v m = putWithKey (\_ x` y` -> f x` y`) k v m

// | /O(log n)/. Insert with a function, combining key, new value and old value.
// @'putWithKey` f key value mp@
// will put the pair (key, value) into @mp@ if key does
// not exist in the map. If the key does exist, the function will
// put the pair @(key,f key new_value old_value)@.
// Note that the key passed to f is the same key passed to 'putWithKey`.
//
// > let f key new_value old_value = (show key) ++ ":" ++ new_value ++ "|" ++ old_value
// > putWithKey f 5 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:xxx|a")]
// > putWithKey f 7 "xxx" (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "xxx")]
// > putWithKey f 5 "xxx" newMap                         == singleton 5 "xxx"

// See Note: Type of local 'go' function
209 210 211
putWithKey :: !(k a a -> a) !k !a !(Map k a) -> Map k a | < k
putWithKey _ kx x Tip = singleton kx x
putWithKey f kx x (Bin sy ky y l r) =
212 213 214 215 216
  if (kx < ky)
    (balanceL ky y (putWithKey f kx x l) r)
    (if (kx > ky)
       (balanceR ky y l (putWithKey f kx x r))
       (Bin sy kx (f kx x y) l r))
217

218 219 220
del :: !k !(Map k a) -> Map k a | < k
del _ Tip = Tip
del k (Bin _ kx x l r) =
221 222 223 224 225
  if (k < kx)
    (balanceR kx x (del k l) r)
    (if (k > kx)
       (balanceL kx x l (del k r))
       (glue l r))
226 227 228 229 230 231 232 233 234

// | /O(log n)/. Update a value at a specific key with the result of the provided function.
// When the key is not
// a member of the map, the original map is returned.
//
// > adjust ("new " ++) 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
// > adjust ("new " ++) 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
// > adjust ("new " ++) 7 newMap                         == newMap

235
adjust :: !(a -> a) !k !(Map k a) -> Map k a | < k
236 237 238 239 240 241 242 243 244 245
adjust f k m = adjustWithKey (\_ 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.
//
// > let f key x = (show key) ++ ":new " ++ x
// > adjustWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
// > adjustWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
// > adjustWithKey f 7 newMap                         == newMap

246
adjustWithKey :: !(k a -> a) !k !(Map k a) -> Map k a | < k
247 248 249 250 251 252 253 254 255 256 257
adjustWithKey f k m = 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@.
//
// > let f x = if x == "a" then Just "new a" else Nothing
// > update f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "new a")]
// > update f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
// > update f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"

258
update :: !(a -> Maybe a) !k !(Map k a) -> Map k a | < k
259 260 261 262 263 264 265 266 267 268 269 270 271
update f k m = updateWithKey (\_ x -> f x) k m

// | /O(log n)/. The expression (@'updateWithKey` 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@.
//
// > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
// > updateWithKey f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "5:new a")]
// > updateWithKey f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
// > updateWithKey f 3 (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"

// See Note: Type of local 'go' function
272 273 274
updateWithKey :: !(k a -> Maybe a) !k !(Map k a) -> Map k a | < k
updateWithKey _ _ Tip = Tip
updateWithKey f k (Bin sx kx x l r) =
275 276 277 278 279 280 281
  if (k < kx)
    (balanceR kx x (updateWithKey f k l) r)
    (if (k > kx)
       (balanceL kx x l (updateWithKey f k r))
       (case f kx x of
          Just x` -> Bin sx kx x` l r
          Nothing -> glue l r))
282 283 284 285 286 287 288 289 290 291 292

// | /O(log n)/. Lookup and update. See also 'updateWithKey`.
// The function returns changed value, if it is updated.
// Returns the original key value if the map entry is deleted.
//
// > let f k x = if x == "a" then Just ((show k) ++ ":new a") else Nothing
// > updateLookupWithKey f 5 (fromList [(5,"a"), (3,"b")]) == (Just "5:new a", fromList [(3, "b"), (5, "5:new a")])
// > updateLookupWithKey f 7 (fromList [(5,"a"), (3,"b")]) == (Nothing,  fromList [(3, "b"), (5, "a")])
// > updateLookupWithKey f 3 (fromList [(5,"a"), (3,"b")]) == (Just "b", singleton 5 "a")

// See Note: Type of local 'go' function
293 294 295
updateLookupWithKey :: !(k a -> Maybe a) !k !(Map k a) -> (Maybe a,Map k a) | < k
updateLookupWithKey _ _ Tip = (Nothing,Tip)
updateLookupWithKey f k (Bin sx kx x l r) =
296
          case lexOrd k kx of
297 298
               LT -> let (found,l`) = updateLookupWithKey f k l in (found,balanceR kx x l` r)
               GT -> let (found,r`) = updateLookupWithKey f k r in (found,balanceL kx x l r`)
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
               EQ -> case f kx x of
                       Just x` -> (Just x`,Bin sx kx x` l r)
                       Nothing -> (Just x,glue l r)

// | /O(log n)/. The expression (@'alter` f k map@) alters the value @x@ at @k@, or absence thereof.
// 'alter` can be used to put, delete, or update a value in a 'Map'.
// In short : @'get' k ('alter` f k m) = f ('get' k m)@.
//
// > let f _ = Nothing
// > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a")]
// > alter f 5 (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
// >
// > let f _ = Just "c"
// > alter f 7 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "a"), (7, "c")]
// > alter f 5 (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "c")]

// See Note: Type of local 'go' function
316 317 318 319 320 321 322 323
alter :: !((Maybe a) -> Maybe a) !k !(Map k a) -> Map k a | < k
alter f k Tip = case f Nothing of
                   Nothing -> Tip
                   Just x  -> singleton k x

alter f k (Bin sx kx x l r) = case lexOrd k kx of
               LT -> balance kx x (alter f k l) r
               GT -> balance kx x l (alter f k r)
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
               EQ -> case f (Just x) of
                       Just x` -> Bin sx kx x` l r
                       Nothing -> glue l r

//////////////////////////////////////////////////////////////////////
//  Indexing
//////////////////////////////////////////////////////////////////////
// | /O(log n)/. Lookup the /index/ of a key, which is its zero-based index in
// the sequence sorted by keys. The index is a number from /0/ up to, but not
// including, the 'mapSize' of the map.
//
// > isJust (getIndex 2 (fromList [(5,"a"), (3,"b")]))   == False
// > fromJust (getIndex 3 (fromList [(5,"a"), (3,"b")])) == 0
// > fromJust (getIndex 5 (fromList [(5,"a"), (3,"b")])) == 1
// > isJust (getIndex 6 (fromList [(5,"a"), (3,"b")]))   == False

// See Note: Type of local 'go' function
341
getIndex :: !k !(Map k a) -> Maybe Int | < k
342 343
getIndex k m = go 0 k m
  where
344
    go :: !Int !k !(Map k a) -> Maybe Int | < k
345 346 347 348 349 350 351 352
    go _   _ Tip  = Nothing
    go idx k (Bin _ kx _ l r) = case lexOrd k kx of
      LT -> go idx k l
      GT -> go (idx + mapSize l + 1) k r
      EQ -> Just (idx + mapSize l)

// | /O(log n)/. Retrieve an element by its /index/, i.e. by its zero-based
// index in the sequence sorted by keys. If the /index/ is out of range (less
Camil Staps's avatar
Camil Staps committed
353
// than zero, greater or equal to 'mapSize' of the map), 'Nothing` is returned.
354
//
355 356 357
// > elemAt 0 (fromList [(5,"a"), (3,"b")]) == Just (3,"b")
// > elemAt 1 (fromList [(5,"a"), (3,"b")]) == Just (5, "a")
// > elemAt 2 (fromList [(5,"a"), (3,"b")]) == Nothing
358

359 360
elemAt :: !Int !(Map k a) -> Maybe (!k, !a)
elemAt _ Tip = Nothing
361
elemAt i (Bin _ kx x l r)
362
  #! mapSizeL = mapSize l
363 364 365
  = case lexOrd i mapSizeL of
      LT -> elemAt i l
      GT -> elemAt (i - mapSizeL - 1) r
366
      EQ -> Just (kx,x)
367 368 369

// | /O(log n)/. Update the element at /index/, i.e. by its zero-based index in
// the sequence sorted by keys. If the /index/ is out of range (less than zero,
370
// greater or equal to 'mapSize' of the map), 'Nothing` is returned.
371
//
372 373 374 375 376 377 378 379 380 381
// > updateAt (\ _ _ -> Just "x") 0    (fromList [(5,"a"), (3,"b")]) == Just (fromList [(3, "x"), (5, "a")])
// > updateAt (\ _ _ -> Just "x") 1    (fromList [(5,"a"), (3,"b")]) == Just (fromList [(3, "b"), (5, "x")])
// > updateAt (\ _ _ -> Just "x") 2    (fromList [(5,"a"), (3,"b")]) == Nothing
// > updateAt (\ _ _ -> Just "x") (-1) (fromList [(5,"a"), (3,"b")]) == Nothing
// > updateAt (\_ _  -> Nothing)  0    (fromList [(5,"a"), (3,"b")]) == Just (singleton 5 "a")
// > updateAt (\_ _  -> Nothing)  1    (fromList [(5,"a"), (3,"b")]) == Just (singleton 3 "b")
// > updateAt (\_ _  -> Nothing)  2    (fromList [(5,"a"), (3,"b")]) == Nothing
// > updateAt (\_ _  -> Nothing)  (-1) (fromList [(5,"a"), (3,"b")]) == Nothing

updateAt :: !(k a -> Maybe a) !Int !(Map k a) -> Maybe (Map k a)
382 383
updateAt f i t =
  case t of
384
    Tip = Nothing
385 386 387
    Bin sx kx x l r
      #! mapSizeL = mapSize l
      = case lexOrd i mapSizeL of
388 389
          LT -> flip (balanceR kx x) r <$> updateAt f i l
          GT -> balanceL kx x l <$> updateAt f (i-mapSizeL-1) r
390
          EQ -> case f kx x of
391 392
                  Just x` -> Just (Bin sx kx x` l r)
                  Nothing -> Just (glue l r)
393 394 395 396 397 398 399 400 401 402


//////////////////////////////////////////////////////////////////////
//  Minimal, Maximal
//////////////////////////////////////////////////////////////////////
// | /O(log n)/. The minimal key of the map. Calls 'abort` if the map is newMap.
//
// > findMin (fromList [(5,"a"), (3,"b")]) == (3,"b")
// > findMin newMap                            Error: newMap map has no minimal element

403
findMin :: !(Map k a) -> (!k, !a)
404 405 406 407 408 409 410 411 412
findMin (Bin _ kx x Tip _)  = (kx,x)
findMin (Bin _ _  _ l _)    = findMin l
findMin Tip                 = abort "Map.findMin: newMap map has no minimal element"

// | /O(log n)/. The maximal key of the map. Calls 'abort` if the map is newMap.
//
// > findMax (fromList [(5,"a"), (3,"b")]) == (5,"a")
// > findMax newMap                            Error: newMap map has no maximal element

413
findMax :: !(Map k a) -> (!k, !a)
414 415 416 417 418 419 420 421 422
findMax (Bin _ kx x _ Tip)  = (kx,x)
findMax (Bin _ _  _ _ r)    = findMax r
findMax Tip                 = abort "Map.findMax: newMap map has no maximal element"

// | /O(log n)/. Delete the minimal key. Returns an newMap map if the map is newMap.
//
// > deleteMin (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(5,"a"), (7,"c")]
// > deleteMin newMap == newMap

423
deleteMin :: !(Map k a) -> Map k a
424 425 426 427 428 429 430 431 432
deleteMin (Bin _ _  _ Tip r)  = r
deleteMin (Bin _ kx x l r)    = balanceR kx x (deleteMin l) r
deleteMin Tip                 = Tip

// | /O(log n)/. Delete the maximal key. Returns an newMap map if the map is newMap.
//
// > deleteMax (fromList [(5,"a"), (3,"b"), (7,"c")]) == fromList [(3,"b"), (5,"a")]
// > deleteMax newMap == newMap

433
deleteMax :: !(Map k a) -> Map k a
434 435 436 437 438 439 440 441 442
deleteMax (Bin _ _  _ l Tip)  = l
deleteMax (Bin _ kx x l r)    = balanceL kx x l (deleteMax r)
deleteMax Tip                 = Tip

// | /O(log n)/. Update the value at the minimal key.
//
// > updateMin (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "Xb"), (5, "a")]
// > updateMin (\ _ -> Nothing)         (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"

443
updateMin :: !(a -> Maybe a) !(Map k a) -> Map k a
444 445 446 447 448 449 450 451
updateMin f m
  = updateMinWithKey (\_ x -> f x) m

// | /O(log n)/. Update the value at the maximal key.
//
// > updateMax (\ a -> Just ("X" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3, "b"), (5, "Xa")]
// > updateMax (\ _ -> Nothing)         (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"

452
updateMax :: !(a -> Maybe a) !(Map k a) -> Map k a
453
updateMax f m = updateMaxWithKey (\_ x -> f x) m
454 455 456 457 458 459 460


// | /O(log n)/. Update the value at the minimal key.
//
// > updateMinWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"3:b"), (5,"a")]
// > updateMinWithKey (\ _ _ -> Nothing)                     (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"

461
updateMinWithKey :: !(k a -> Maybe a) !(Map k a) -> Map k a
462 463 464 465 466 467 468 469 470 471 472
updateMinWithKey _ Tip                 = Tip
updateMinWithKey f (Bin sx kx x Tip r) = case f kx x of
                                           Nothing -> r
                                           Just x` -> Bin sx kx x` Tip r
updateMinWithKey f (Bin _ kx x l r)    = balanceR kx x (updateMinWithKey f l) r

// | /O(log n)/. Update the value at the maximal key.
//
// > updateMaxWithKey (\ k a -> Just ((show k) ++ ":" ++ a)) (fromList [(5,"a"), (3,"b")]) == fromList [(3,"b"), (5,"5:a")]
// > updateMaxWithKey (\ _ _ -> Nothing)                     (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"

473
updateMaxWithKey :: !(k a -> Maybe a) !(Map k a) -> Map k a
474 475 476 477 478 479 480 481 482 483 484 485
updateMaxWithKey _ Tip                 = Tip
updateMaxWithKey f (Bin sx kx x l Tip) = case f kx x of
                                           Nothing -> l
                                           Just x` -> Bin sx kx x` l Tip
updateMaxWithKey f (Bin _ kx x l r)    = balanceL kx x l (updateMaxWithKey f r)

// | /O(log n)/. Retrieves the minimal (key,value) pair of the map, and
// the map stripped of that element, or 'Nothing' if passed an newMap map.
//
// > minViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((3,"b"), singleton 5 "a")
// > minViewWithKey newMap == Nothing

486
minViewWithKey :: !(Map k a) -> Maybe (!(!k, !a), !Map k a)
487 488 489 490 491 492 493 494 495
minViewWithKey Tip = Nothing
minViewWithKey x   = Just (deleteFindMin x)

// | /O(log n)/. Retrieves the maximal (key,value) pair of the map, and
// the map stripped of that element, or 'Nothing' if passed an newMap map.
//
// > maxViewWithKey (fromList [(5,"a"), (3,"b")]) == Just ((5,"a"), singleton 3 "b")
// > maxViewWithKey newMap == Nothing

496
maxViewWithKey :: !(Map k a) -> Maybe (!(!k, !a), !Map k a)
497 498 499 500 501 502 503 504 505 506
maxViewWithKey Tip = Nothing
maxViewWithKey x   = Just (deleteFindMax x)

// | /O(log n)/. Retrieves the value associated with minimal key of the
// map, and the map stripped of that element, or 'Nothing' if passed an
// newMap map.
//
// > minView (fromList [(5,"a"), (3,"b")]) == Just ("b", singleton 5 "a")
// > minView newMap == Nothing

507
minView :: !(Map k a) -> Maybe (!a, !Map k a)
508 509 510 511 512 513 514 515 516
minView Tip = Nothing
minView x   = Just (first snd (deleteFindMin x))

// | /O(log n)/. Retrieves the value associated with maximal key of the
// map, and the map stripped of that element, or 'Nothing' if passed an
//
// > maxView (fromList [(5,"a"), (3,"b")]) == Just ("a", singleton 3 "b")
// > maxView newMap == Nothing

517
maxView :: !(Map k a) -> Maybe (!a, !Map k a)
518 519 520 521
maxView Tip = Nothing
maxView x   = Just (first snd (deleteFindMax x))

// Update the 1st component of a tuple (special case of Control.Arrow.first)
522
first :: !(a -> b) !(!a, !c) -> (!b, !c)
523 524 525 526 527 528 529 530 531 532 533 534 535
first f (x,y) = (f x, y)

//////////////////////////////////////////////////////////////////////
//  Union.
//////////////////////////////////////////////////////////////////////
// | The union of a list of maps:
//   (@'unions' == 'Prelude.foldl` 'union' 'newMap`@).
//
// > unions [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
// >     == fromList [(3, "b"), (5, "a"), (7, "C")]
// > unions [(fromList [(5, "A3"), (3, "B3")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "a"), (3, "b")])]
// >     == fromList [(3, "B3"), (5, "A3"), (7, "C")]

536
//unions :: ![Map k a] -> Map k a | < k
537 538 539 540 541 542 543

// | The union of a list of maps, with a combining operation:
//   (@'unionsWith' f == 'Prelude.foldl` ('unionWith' f) 'newMap`@).
//
// > unionsWith (++) [(fromList [(5, "a"), (3, "b")]), (fromList [(5, "A"), (7, "C")]), (fromList [(5, "A3"), (3, "B3")])]
// >     == fromList [(3, "bB3"), (5, "aAA3"), (7, "C")]

544
//unionsWith :: !(a a -> a) ![Map k a] -> Map k a | < k
545 546 547 548 549 550 551 552 553

// | /O(n+m)/.
// The expression (@'union' t1 t2@) takes the left-biased union of @t1@ and @t2@.
// It prefers @t1@ when duplicate keys are encountered,
// i.e. (@'union' == 'unionWith' 'const`=:).
// The implementation uses the efficient /hedge-union/ algorithm.
//
// > union (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "a"), (7, "C")]

554
union :: !(Map k a) !(Map k a) -> Map k a | < k
555 556 557 558
union Tip t2  = t2
union t1 Tip  = t1
union t1 t2 = hedgeUnion Nothing Nothing t1 t2

559
unions :: ![Map k a] -> Map k a | < k
Steffen Michels's avatar
Steffen Michels committed
560
unions ts = foldl union newMap ts
561 562

unionsWith :: !(a a -> a) ![Map k a] -> Map k a | < k
Steffen Michels's avatar
Steffen Michels committed
563
unionsWith f ts = foldl (unionWith f) newMap ts
564 565

unionWith :: !(a a -> a) !(Map k a) !(Map k a) -> Map k a | < k
566 567 568 569
unionWith f m1 m2 = unionWithKey (appUnion f) m1 m2
  where
  appUnion :: !(a a -> a) k !a !a -> a
  appUnion f _ x y = f x y
570 571

unionWithKey :: !(k a a -> a) !(Map k a) !(Map k a) -> Map k a | < k
572 573 574 575
unionWithKey f t1 t2 = mergeWithKey (appUnion f) id id t1 t2
  where
  appUnion :: !(k a a -> a) !k !a !a -> Maybe a
  appUnion f k x y = Just (f k x y)
576

577
// left-biased hedge union
578
hedgeUnion :: !(Maybe a) !(Maybe a) !(Map a b) !(Map a b) -> Map a b | < a
579 580 581 582
hedgeUnion _   _   t1  Tip = t1
hedgeUnion blo bhi Tip (Bin _ kx x l r) = link kx x (filterGt blo l) (filterLt bhi r)
hedgeUnion _   _   t1  (Bin _ kx x Tip Tip) = putR kx x t1  // According to benchmarks, this special case increases
                                                              // performance up to 30%. It does not help in difference or intersection.
583 584 585 586
hedgeUnion blo bhi (Bin _ kx x l r) t2
  #! bmi = Just kx
  = link kx x (hedgeUnion blo bmi l (trim blo bmi t2))
              (hedgeUnion bmi bhi r (trim bmi bhi t2))
Camil Staps's avatar
Camil Staps committed
587
hedgeUnion _ _ _ _ = abort "error in hedgeUnion\n"
588 589 590 591 592 593 594 595

//////////////////////////////////////////////////////////////////////
//  Union with a combining function
//////////////////////////////////////////////////////////////////////
// | /O(n+m)/. Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
//
// > unionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "aA"), (7, "C")]

596
//unionWith :: !(a a -> a) !(Map k a) !(Map k a) -> Map k a | < k
597 598 599 600 601 602 603

// | /O(n+m)/.
// Union with a combining function. The implementation uses the efficient /hedge-union/ algorithm.
//
// > let f key left_value right_value = (show key) ++ ":" ++ left_value ++ "|" ++ right_value
// > unionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == fromList [(3, "b"), (5, "5:a|A"), (7, "C")]

604
//unionWithKey :: !(k a a -> a) !(Map k a) !(Map k a) -> Map k a | < k
605 606 607 608 609 610 611 612 613 614

//////////////////////////////////////////////////////////////////////
//  Difference
//////////////////////////////////////////////////////////////////////
// | /O(n+m)/. Difference of two maps.
// Return elements of the first map not existing in the second map.
// The implementation uses an efficient /hedge/ algorithm comparable with /hedge-union/.
//
// > difference (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 3 "b"

615
difference :: !(Map k a) !(Map k b) -> Map k a | < k
616 617 618 619
difference Tip _   = Tip
difference t1 Tip  = t1
difference t1 t2   = hedgeDiff Nothing Nothing t1 t2

620
hedgeDiff :: !(Maybe a) !(Maybe a) !(Map a b) !(Map a c) -> Map a b | < a
621 622
hedgeDiff _   _   Tip              _ = Tip
hedgeDiff blo bhi (Bin _ kx x l r) Tip = link kx x (filterGt blo l) (filterLt bhi r)
623 624 625
hedgeDiff blo bhi t (Bin _ kx _ l r)
  #! bmi = Just kx
  = merge (hedgeDiff blo bmi (trim blo bmi t) l) (hedgeDiff bmi bhi (trim bmi bhi t) r)
Camil Staps's avatar
Camil Staps committed
626
hedgeDiff _ _ _ _ = abort "error in hedgeDiff\n"
627 628 629 630 631 632 633 634 635 636 637 638

// | /O(n+m)/. Difference with a combining function.
// When two equal keys are
// encountered, the combining function is applied to the values of these keys.
// 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/.
//
// > let f al ar = if al == "b" then Just (al ++ ":" ++ ar) else Nothing
// > differenceWith f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (7, "C")])
// >     == singleton 3 "b:B"

639
differenceWith :: !(a b -> Maybe a) !(Map k a) !(Map k b) -> Map k a | < k
640 641 642 643 644 645 646 647 648 649 650 651 652
differenceWith f m1 m2
  = differenceWithKey (\_ 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/.
//
// > let f k al ar = if al == "b" then Just ((show k) ++ ":" ++ al ++ "|" ++ ar) else Nothing
// > differenceWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (3, "B"), (10, "C")])
// >     == singleton 3 "3:b|B"

653
differenceWithKey :: !(k a b -> Maybe a) !(Map k a) !(Map k b) -> Map k a | < k
654 655 656 657 658 659 660 661 662 663 664 665 666 667
differenceWithKey f t1 t2 = mergeWithKey f id (const Tip) t1 t2


//////////////////////////////////////////////////////////////////////
//  Intersection
//////////////////////////////////////////////////////////////////////
// | /O(n+m)/. Intersection of two maps.
// Return data in the first map for the keys existing in both maps.
// (@'intersection' m1 m2 == 'intersectionWith' 'const` m1 m2@).
// The implementation uses an efficient /hedge/ algorithm comparable with
// /hedge-union/.
//
// > intersection (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "a"

668
intersection :: !(Map k a) !(Map k b) -> Map k a | < k
669 670 671 672
intersection Tip _ = Tip
intersection _ Tip = Tip
intersection t1 t2 = hedgeInt Nothing Nothing t1 t2

673
hedgeInt :: !(Maybe k) !(Maybe k) !(Map k a) !(Map k b) -> Map k a | < k
674 675
hedgeInt _ _ _   Tip = Tip
hedgeInt _ _ Tip _   = Tip
676 677 678 679 680 681
hedgeInt blo bhi (Bin _ kx x l r) t2
  #! bmi = Just kx
  #! l` = hedgeInt blo bmi l (trim blo bmi t2)
  #! r` = hedgeInt bmi bhi r (trim bmi bhi t2)
  | member kx t2 = link kx x l` r`
  | otherwise    = merge l` r`
682 683 684 685 686 687

// | /O(n+m)/. Intersection with a combining function.  The implementation uses
// an efficient /hedge/ algorithm comparable with /hedge-union/.
//
// > intersectionWith (++) (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "aA"

688
intersectionWith :: !(a b -> c) !(Map k a) !(Map k b) -> Map k c | < k
689 690 691 692 693 694 695 696 697 698
intersectionWith f m1 m2
  = intersectionWithKey (\_ x y -> f x y) m1 m2

// | /O(n+m)/. Intersection with a combining function.  The implementation uses
// an efficient /hedge/ algorithm comparable with /hedge-union/.
//
// > let f k al ar = (show k) ++ ":" ++ al ++ "|" ++ ar
// > intersectionWithKey f (fromList [(5, "a"), (3, "b")]) (fromList [(5, "A"), (7, "C")]) == singleton 5 "5:a|A"


699
intersectionWithKey :: !(k a b -> c) !(Map k a) !(Map k b) -> Map k c | < k
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
intersectionWithKey f t1 t2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const Tip) (const Tip) t1 t2


//////////////////////////////////////////////////////////////////////
//  MergeWithKey
//////////////////////////////////////////////////////////////////////

// | /O(n+m)/. A high-performance universal combining function. This function
// is used to define 'unionWith', 'unionWithKey`, 'differenceWith',
// 'differenceWithKey`, 'intersectionWith', 'intersectionWithKey` and can be
// used to define other custom combine functions.
//
// Please make sure you know what is going on when using 'mergeWithKey`,
// otherwise you can be surprised by unexpected code growth or even
// corruption of the data structure.
//
// When 'mergeWithKey` is given three arguments, it is inlined to the call
// site. You should therefore use 'mergeWithKey` only to define your custom
// combining functions. For example, you could define 'unionWithKey`,
// 'differenceWithKey` and 'intersectionWithKey` as
//
// > myUnionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) id id m1 m2
// > myDifferenceWithKey f m1 m2 = mergeWithKey f id (const newMap) m1 m2
// > myIntersectionWithKey f m1 m2 = mergeWithKey (\k x1 x2 -> Just (f k x1 x2)) (const newMap) (const newMap) m1 m2
//
// When calling @'mergeWithKey` combine only1 only2@, a function combining two
// 'IntMap's is created, such that
//
// * if a key is present in both maps, it is passed with both corresponding
//   values to the @combine@ function. Depending on the result, the key is either
//   present in the result with specified value, or is left out;
//
// * a nonnewMap subtree present only in the first map is passed to @only1@ and
//   the output is added to the result;
//
// * a nonnewMap subtree present only in the second map is passed to @only2@ and
//   the output is added to the result.
//
// The @only1@ and @only2@ methods /must return a map with a subset (possibly newMap) of the keys of the given map/.
// The values can be modified arbitrarily. Most common variants of @only1@ and
// @only2@ are 'id' and @'const` 'newMap`@, but for example @'map' f@ or
// @'filterWithKey` f@ could be used for any @f@.

743 744
mergeWithKey :: !(k a b -> Maybe c) !((Map k a) -> Map k c) !((Map k b) -> Map k c)
             !(Map k a) !(Map k b) -> Map k c | < k
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
mergeWithKey f g1 g2 Tip t2 = g2 t2
mergeWithKey f g1 g2 t1 Tip = g1 t1
mergeWithKey f g1 g2 t1 t2 = hedgeMerge f g1 g2 Nothing Nothing t1 t2

hedgeMerge :: !(a b c -> Maybe d) !((Map a b) -> Map a d) !((Map a c) -> Map a d)
              !(Maybe a) !(Maybe a) !(Map a b) !(Map a c) -> Map a d | < a
hedgeMerge f g1 g2 _   _   t1  Tip = g1 t1
hedgeMerge f g1 g2 blo bhi Tip (Bin _ kx x l r) = g2 (link kx x (filterGt blo l) (filterLt bhi r))
hedgeMerge f g1 g2 blo bhi (Bin _ kx x l r) t2
  #! bmi              = Just kx
  #! l`               = hedgeMerge f g1 g2 blo bmi l (trim blo bmi t2)
  #! (found, trim_t2) = trimLookupLo kx bhi t2
  #! r`               = hedgeMerge f g1 g2 bmi bhi r trim_t2
  = case found of
      Nothing -> case g1 (singleton kx x) of
                   Tip -> merge l` r`
                   (Bin _ _ x` Tip Tip) -> link kx x` l` r`
                   _ -> abort "mergeWithKey: Given function only1 does not fulfil required conditions (see documentation)"
      Just x2 -> case f kx x x2 of
                   Nothing -> merge l` r`
                   Just x` -> link kx x` l` r`
Camil Staps's avatar
Camil Staps committed
766
hedgeMerge _ _ _ _ _ _ _ = abort "error in hedgeMerge\n"
767 768 769 770 771 772 773

//////////////////////////////////////////////////////////////////////
//  Submap
//////////////////////////////////////////////////////////////////////
// | /O(n+m)/.
// This function is defined as (@'isSubmapOf' = 'isSubmapOfBy` (==)@).
//
774
isSubmapOf :: !(Map k a) !(Map k a) -> Bool | < k & Eq a
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
isSubmapOf m1 m2 = isSubmapOfBy (==) m1 m2

/* | /O(n+m)/.
 The expression (@'isSubmapOfBy` 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':

 > isSubmapOfBy (==) (fromList [('a`,1)]) (fromList [('a`,1),('b`,2)])
 > isSubmapOfBy (<=) (fromList [('a`,1)]) (fromList [('a`,1),('b`,2)])
 > isSubmapOfBy (==) (fromList [('a`,1),('b`,2)]) (fromList [('a`,1),('b`,2)])

 But the following are all 'False':

 > isSubmapOfBy (==) (fromList [('a`,2)]) (fromList [('a`,1),('b`,2)])
 > isSubmapOfBy (<)  (fromList [('a`,1)]) (fromList [('a`,1),('b`,2)])
 > isSubmapOfBy (==) (fromList [('a`,1),('b`,2)]) (fromList [('a`,1)])

*/
794
isSubmapOfBy :: !(a b -> Bool) !(Map k a) !(Map k b) -> Bool | < k
795 796 797
isSubmapOfBy f t1 t2
  = (mapSize t1 <= mapSize t2) && (submap` f t1 t2)

798
submap` :: !(b c -> Bool) !(Map a b) !(Map a c) -> Bool | < a
799 800 801 802 803 804 805 806
submap` _ Tip _ = True
submap` _ _ Tip = False
submap` f (Bin _ kx x l r) t
  = case found of
      Nothing -> False
      Just y  -> f x y && submap` f l lt && submap` f r gt
  where
    (lt,found,gt) = splitLookup kx t
Camil Staps's avatar
Camil Staps committed
807
submap` _ _ _ = abort "error in submap`\n"
808 809 810

// | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
// Defined as (@'isProperSubmapOf' = 'isProperSubmapOfBy` (==)@).
811
isProperSubmapOf :: !(Map k a) !(Map k a) -> Bool | < k & Eq a
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
isProperSubmapOf m1 m2
  = isProperSubmapOfBy (==) m1 m2

/* | /O(n+m)/. Is this a proper submap? (ie. a submap but not equal).
 The expression (@'isProperSubmapOfBy` 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':

  > isProperSubmapOfBy (==) (fromList [(1,1)]) (fromList [(1,1),(2,2)])
  > isProperSubmapOfBy (<=) (fromList [(1,1)]) (fromList [(1,1),(2,2)])

 But the following are all 'False':

  > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1),(2,2)])
  > isProperSubmapOfBy (==) (fromList [(1,1),(2,2)]) (fromList [(1,1)])
  > isProperSubmapOfBy (<)  (fromList [(1,1)])       (fromList [(1,1),(2,2)])


*/
833
isProperSubmapOfBy :: !(a b -> Bool) !(Map k a) !(Map k b) -> Bool | < k
834 835 836 837 838 839 840 841 842 843 844 845
isProperSubmapOfBy f t1 t2
  = (mapSize t1 < mapSize t2) && (submap` f t1 t2)

//////////////////////////////////////////////////////////////////////
//  Filter and partition
//////////////////////////////////////////////////////////////////////
// | /O(n)/. Filter all values that satisfy the predicate.
//
// > filter (> "a") (fromList [(5,"a"), (3,"b")]) == singleton 3 "b"
// > filter (> "x") (fromList [(5,"a"), (3,"b")]) == newMap
// > filter (< "a") (fromList [(5,"a"), (3,"b")]) == newMap

846
filter :: !(a -> Bool) !(Map k a) -> Map k a
847
filter p m = filterWithKey (\_ x -> p x) m
848 849 850 851 852

// | /O(n)/. Filter all keys\/values that satisfy the predicate.
//
// > filterWithKey (\k _ -> k > 4) (fromList [(5,"a"), (3,"b")]) == singleton 5 "a"

853
// TODO : Optimize?
854
filterWithKey :: !(k a -> Bool) !(Map k a) -> Map k a
855 856 857 858 859 860 861 862 863 864 865 866 867
filterWithKey _ Tip = Tip
filterWithKey p (Bin _ kx x l r)
  | p kx x    = link 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 (> "a") (fromList [(5,"a"), (3,"b")]) == (singleton 3 "b", singleton 5 "a")
// > partition (< "x") (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], newMap)
// > partition (> "x") (fromList [(5,"a"), (3,"b")]) == (newMap, fromList [(3, "b"), (5, "a")])

868
partition :: !(a -> Bool) !(Map k a) -> (!Map k a, !Map k a)
869 870 871 872 873 874 875 876 877 878 879
partition p m
  = partitionWithKey (\_ 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 (\ k _ -> k > 3) (fromList [(5,"a"), (3,"b")]) == (singleton 5 "a", singleton 3 "b")
// > partitionWithKey (\ k _ -> k < 7) (fromList [(5,"a"), (3,"b")]) == (fromList [(3, "b"), (5, "a")], newMap)
// > partitionWithKey (\ k _ -> k > 7) (fromList [(5,"a"), (3,"b")]) == (newMap, fromList [(3, "b"), (5, "a")])

880 881 882 883 884 885 886
partitionWithKey :: !(k a -> Bool) !(Map k a) -> (!Map k a, !Map k a)
partitionWithKey _ Tip = (Tip, Tip)
partitionWithKey p (Bin _ kx x l r)
  #! (l1, l2) = partitionWithKey p l
  #! (r1, r2) = partitionWithKey p r
  | p kx x    = (link kx x l1 r1, merge l2 r2)
  | otherwise = (merge l1 r1, link kx x l2 r2)
887 888 889 890 891 892

// | /O(n)/. Map values and collect the 'Just` results.
//
// > let f x = if x == "a" then Just "new a" else Nothing
// > mapMaybe f (fromList [(5,"a"), (3,"b")]) == singleton 5 "new a"

893
mapMaybe :: !(a -> Maybe b) !(Map k a) -> Map k b
894 895 896 897 898 899 900
mapMaybe f m = mapMaybeWithKey (\_ x -> f x) m

// | /O(n)/. Map keys\/values and collect the 'Just` results.
//
// > let f k _ = if k < 5 then Just ("key : " ++ (show k)) else Nothing
// > mapMaybeWithKey f (fromList [(5,"a"), (3,"b")]) == singleton 3 "key : 3"

901
mapMaybeWithKey :: !(k a -> Maybe b) !(Map k a) -> Map k b
902 903
mapMaybeWithKey _ Tip = Tip
mapMaybeWithKey f (Bin _ kx x l r) = case f kx x of
904 905
                                       Just y  -> link kx y (mapMaybeWithKey f l) (mapMaybeWithKey f r)
                                       Nothing -> merge (mapMaybeWithKey f l) (mapMaybeWithKey f r)
906 907 908 909 910 911 912 913 914 915

// | /O(n)/. Map values and separate the 'Left` and 'Right` results.
//
// > let f a = if a < "c" then Left a else Right a
// > mapEither f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
// >     == (fromList [(3,"b"), (5,"a")], fromList [(1,"x"), (7,"z")])
// >
// > mapEither (\ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
// >     == (newMap, fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])

916 917
mapEither :: !(a -> Either b c) !(Map k a) -> (!Map k b, !Map k c)
mapEither f m = mapEitherWithKey (\_ x -> f x) m
918 919 920 921 922 923 924 925 926 927

// | /O(n)/. Map keys\/values and separate the 'Left` and 'Right` results.
//
// > let f k a = if k < 5 then Left (k * 2) else Right (a ++ a)
// > mapEitherWithKey f (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
// >     == (fromList [(1,2), (3,6)], fromList [(5,"aa"), (7,"zz")])
// >
// > mapEitherWithKey (\_ a -> Right a) (fromList [(5,"a"), (3,"b"), (1,"x"), (7,"z")])
// >     == (newMap, fromList [(1,"x"), (3,"b"), (5,"a"), (7,"z")])

928 929 930 931 932 933 934 935
mapEitherWithKey :: !(k a -> Either b c) !(Map k a) -> (!Map k b, !Map k c)
mapEitherWithKey _ Tip = (Tip, Tip)
mapEitherWithKey f (Bin _ kx x l r)
  #! (l1, l2) = mapEitherWithKey f l
  #! (r1, r2) = mapEitherWithKey f r
  = case f kx x of
      Left y  -> (link kx y l1 r1, merge l2 r2)
      Right z -> (merge l1 r1, link kx z l2 r2)
936

937 938 939 940 941 942 943
//////////////////////////////////////////////////////////////////////
//  Mapping
//////////////////////////////////////////////////////////////////////
// | /O(n)/. Map a function over all values in the map.
//
// > map (++ "x") (fromList [(5,"a"), (3,"b")]) == fromList [(3, "bx"), (5, "ax")]

944
map :: !(a -> b) !(Map k a) -> Map k b
945 946 947 948 949 950 951 952
map _ Tip = Tip
map f (Bin sx kx x l r) = Bin sx kx (f x) (map f l) (map f r)

// | /O(n)/. Map a function over all values in the map.
//
// > let f key x = (show key) ++ ":" ++ x
// > mapWithKey f (fromList [(5,"a"), (3,"b")]) == fromList [(3, "3:b"), (5, "5:a")]

953
mapWithKey :: !(k a -> b) !(Map k a) -> Map k b
954 955 956 957 958 959 960 961 962 963
mapWithKey _ Tip = Tip
mapWithKey f (Bin sx kx x l r) = Bin sx kx (f kx x) (mapWithKey f l) (mapWithKey f r)

// | /O(n)/.
// @'traverseWithKey` f s == 'fromList` <$> 'traverse' (\(k, v) -> (,) k <$> f k v) ('toList` m)@
// That is, behaves exactly like a regular 'traverse' except that the traversing
// function also has access to the key associated with a value.
//
// > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(1, 'a`), (5, 'e')]) == Just (fromList [(1, 'b`), (5, 'f')])
// > traverseWithKey (\k v -> if odd k then Just (succ v) else Nothing) (fromList [(2, 'c')])           == Nothing
964 965 966 967
traverseWithKey :: !(k a -> t b) !(Map k a) -> t (Map k b) | Applicative t
traverseWithKey _ Tip = pure Tip
traverseWithKey f (Bin 1 k v _ _) = (\v` -> Bin 1 k v` Tip Tip) <$> f k v
traverseWithKey f (Bin s k v l r) = flip (Bin s k) <$> traverseWithKey f l <*> f k v <*> traverseWithKey f r
968 969 970 971 972 973 974

// | /O(n)/. The function 'mapAccum' threads an accumulating
// argument through the map in ascending order of keys.
//
// > let f a b = (a ++ b, b ++ "X")
// > mapAccum f "Everything: " (fromList [(5,"a"), (3,"b")]) == ("Everything: ba", fromList [(3, "bX"), (5, "aX")])

975 976
mapAccum :: !(a b -> (!a, !c)) !a !(Map k b) -> (!a, !Map k c)
mapAccum f a m = mapAccumWithKey (\a` _ x` -> f a` x`) a m
977 978 979 980 981 982 983

// | /O(n)/. The function 'mapAccumWithKey` threads an accumulating
// argument through the map in ascending order of keys.
//
// > let f a k b = (a ++ " " ++ (show k) ++ "-" ++ b, b ++ "X")
// > mapAccumWithKey f "Everything:" (fromList [(5,"a"), (3,"b")]) == ("Everything: 3-b 5-a", fromList [(3, "bX"), (5, "aX")])

984 985
mapAccumWithKey :: !(a k b -> (!a, !c)) !a !(Map k b) -> (!a, !Map k c)
mapAccumWithKey f a t = mapAccumL f a t
986 987 988

// | /O(n)/. The function 'mapAccumL' threads an accumulating
// argument through the map in ascending order of keys.
989
mapAccumL :: !(a k b -> (!a, !c)) !a !(Map k b) -> (!a, !Map k c)
990
mapAccumL _ a Tip               = (a,Tip)
991 992 993 994 995
mapAccumL f a (Bin sx kx x l r)
  #! (a1,l`) = mapAccumL f a l
  #! (a2,x`) = f a1 kx x
  #! (a3,r`) = mapAccumL f a2 r
  = (a3, Bin sx kx x` l` r`)
996 997 998

// | /O(n)/. The function 'mapAccumR' threads an accumulating
// argument through the map in descending order of keys.
999
mapAccumRWithKey :: !(a k b -> (!a, !c)) !a !(Map k b) -> (!a, !Map k c)
1000
mapAccumRWithKey _ a Tip = (a,Tip)
1001 1002 1003 1004 1005
mapAccumRWithKey f a (Bin sx kx x l r)
  #! (a1,r`) = mapAccumRWithKey f a r
  #! (a2,x`) = f a1 kx x
  #! (a3,l`) = mapAccumRWithKey f a2 l
  = (a3, Bin sx kx x` l` r`)
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

// | /O(n*log n)/.
// @'mapKeys' f s@ is the map obtained by applying @f@ to each key of @s@.
//
// The mapSize of the result may be smaller if @f@ maps two or more distinct
// keys to the same new key.  In this case the value at the greatest of the
// original keys is retained.
//
// > mapKeys (+ 1) (fromList [(5,"a"), (3,"b")])                        == fromList [(4, "b"), (6, "a")]
// > mapKeys (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "c"
// > mapKeys (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "c"

1018
mapKeys :: !(k1 -> k2) !(Map k1 a) -> Map k2 a | < k1 & < k2 & == k1 & == k2
1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
mapKeys f m = fromList (foldrWithKey (\k x xs -> [(f k, x) : xs]) [] m)

// | /O(n*log n)/.
// @'mapKeysWith' c f s@ is the map obtained by applying @f@ to each key of @s@.
//
// The mapSize of the result may be smaller if @f@ maps two or more distinct
// keys to the same new key.  In this case the associated values will be
// combined using @c@.
//
// > mapKeysWith (++) (\ _ -> 1) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 1 "cdab"
// > mapKeysWith (++) (\ _ -> 3) (fromList [(1,"b"), (2,"a"), (3,"d"), (4,"c")]) == singleton 3 "cdab"

1031
mapKeysWith :: !(a a -> a) !(k1 -> k2) !(Map k1 a) -> Map k2 a | < k1 & < k2
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
mapKeysWith c f m = fromListWith c (foldrWithKey (\k x xs -> [(f k, x) : xs]) [] m)


// | /O(n)/.
// @'mapKeysMonotonic' f s == 'mapKeys' f s@, but works only when @f@
// is strictly monotonic.
// That is, for any values @x@ and @y@, if @x@ < @y@ then @f x@ < @f y@.
// /The precondition is not checked./
// Semi-formally, we have:
//
// > and [x < y ==> f x < f y | x <- ls, y <- ls]
// >                     ==> mapKeysMonotonic f s == mapKeys f s
// >     where ls = keys s
//
// This means that @f@ maps distinct original keys to distinct resulting keys.
// This function has better performance than 'mapKeys'.
//
// > mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")]) == fromList [(6, "b"), (10, "a")]
// > valid (mapKeysMonotonic (\ k -> k * 2) (fromList [(5,"a"), (3,"b")])) == True
// > valid (mapKeysMonotonic (\ _ -> 1)     (fromList [(5,"a"), (3,"b")])) == False

1053
mapKeysMonotonic :: !(k1 -> k2) !(Map k1 a) -> Map k2 a
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
mapKeysMonotonic _ Tip = Tip
mapKeysMonotonic f (Bin sz k x l r) =
    Bin sz (f k) x (mapKeysMonotonic f l) (mapKeysMonotonic f r)

//////////////////////////////////////////////////////////////////////
//  Folds
//////////////////////////////////////////////////////////////////////

// | /O(n)/. Fold the values in the map using the given right-associative
// binary operator, such that @'foldr` f z == 'Prelude.foldr` f z . 'elems'@.
//
// For example,
//
// > elems map = foldr (:) [] map
//
// > let f a len = len + (length a)
// > foldr f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
1071 1072 1073
foldr :: !(a b -> b) !b (Map k a) -> b
foldr f z` Tip             = z`
foldr f z` (Bin _ _ x l r) = foldr f (f x (foldr f z` r)) l
1074 1075 1076 1077

// | /O(n)/. A strict version of 'foldr`. Each application of the operator is
// evaluated before using the result in the next application. This
// function is strict in the starting value.
1078 1079 1080
foldr` :: !(a b -> b) !b !(Map k a) -> b
foldr` f z` Tip             = z`
foldr` f z` (Bin _ _ x l r) = foldr` f (f x (foldr` f z` r)) l
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

// | /O(n)/. Fold the values in the map using the given left-associative
// binary operator, such that @'foldl` f z == 'Prelude.foldl` f z . 'elems'@.
//
// For example,
//
// > elems = reverse . foldl (flip (:)) []
//
// > let f len a = len + (length a)
// > foldl f 0 (fromList [(5,"a"), (3,"bbb")]) == 4
Steffen Michels's avatar
Steffen Michels committed
1091
/*foldl :: !(a b -> a) !a !(Map k b) -> a
1092
foldl f z` Tip             = z`
Steffen Michels's avatar
Steffen Michels committed
1093
foldl f z` (Bin _ _ x l r) = foldl f (f (foldl f z` l) x) r*/
1094 1095 1096 1097

// | /O(n)/. A strict version of 'foldl`. Each application of the operator is
// evaluated before using the result in the next application. This
// function is strict in the starting value.
1098 1099 1100
foldl` :: !(a b -> a) !a (Map k b) -> a
foldl` f z` Tip             = z`
foldl` f z` (Bin _ _ x l r) = foldl` f (f (foldl` f z` l) x) r
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

// | /O(n)/. Fold the keys and values in the map using the given right-associative
// binary operator, such that
// @'foldrWithKey` f z == 'Prelude.foldr` ('uncurry` f) z . 'toAscList`=:.
//
// For example,
//
// > keys map = foldrWithKey (\k x ks -> k:ks) [] map
//
// > let f k a result = result ++ "(" ++ (show k) ++ ":" ++ a ++ ")"
// > foldrWithKey f "Map: " (fromList [(5,"a"), (3,"b")]) == "Map: (5:a)(3:b)"
1112 1113 1114
foldrWithKey :: !(k v u:a -> u:a) !u:a !(Map k v) -> u:a
foldrWithKey f z` Tip              = z`
foldrWithKey f z` (Bin _ kx x l r) = foldrWithKey f (f kx x (foldrWithKey f z` r)) l
1115 1116 1117 1118

// | /O(n)/. A strict version of 'foldrWithKey`. Each application of the operator is
// evaluated before using the result in the next application. This
// function is strict in the starting value.