54ff2f6510b0a5d4f5a45857eddf175acf5d1ca5
[ghc-base.git] / Data / FiniteMap.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.FiniteMap
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  provisional
9 -- Portability :  portable
10 --
11 -- A finite map implementation, derived from the paper:
12 --         /Efficient sets: a balancing act/, S. Adams,
13 --         Journal of functional programming 3(4) Oct 1993, pp553-562
14 --
15 -----------------------------------------------------------------------------
16
17 -- ToDo: clean up, remove the COMPILING_GHC stuff.
18
19 -- The code is SPECIALIZEd to various highly-desirable types (e.g., Id)
20 -- near the end (only \tr{#ifdef COMPILING_GHC}).
21
22 #ifdef COMPILING_GHC
23 #include "HsVersions.h"
24 #define IF_NOT_GHC(a) {--}
25 #else
26 #define ASSERT(e) {--}
27 #define IF_NOT_GHC(a) a
28 #define COMMA ,
29 #define _tagCmp compare
30 #define _LT LT
31 #define _GT GT
32 #define _EQ EQ
33 #endif
34
35 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)/* NB NB NB */
36 #define OUTPUTABLE_key , Outputable key
37 #else
38 #define OUTPUTABLE_key {--}
39 #endif
40
41 module Data.FiniteMap (
42         -- * The @FiniteMap@ type
43         FiniteMap,              -- abstract type
44
45         -- * Construction
46         emptyFM, unitFM, listToFM,
47
48         -- * Lookup operations
49         lookupFM, lookupWithDefaultFM,
50         elemFM,
51
52         -- * Adding elements
53         addToFM,
54         addToFM_C,
55         addListToFM,
56         addListToFM_C,
57
58         -- * Deleting elements
59         IF_NOT_GHC(delFromFM COMMA)
60         delListFromFM,
61
62         -- * Combination
63         plusFM,
64         plusFM_C,
65
66         -- * Extracting information
67         fmToList, keysFM, eltsFM,
68         sizeFM, isEmptyFM,
69
70         -- * Other operations
71         minusFM,
72         foldFM,
73         IF_NOT_GHC(intersectFM COMMA)
74         IF_NOT_GHC(intersectFM_C COMMA)
75         IF_NOT_GHC(mapFM COMMA filterFM COMMA)
76
77         foldFM_GE, fmToList_GE, keysFM_GE, eltsFM_GE
78
79 #ifdef COMPILING_GHC
80         , bagToFM
81 #endif
82     ) where
83
84 import Data.Maybe ( isJust )
85 #ifdef __GLASGOW_HASKELL__
86 import GHC.Base
87 #endif
88
89 #ifdef COMPILING_GHC
90 IMP_Ubiq(){-uitous-}
91 # ifdef DEBUG
92 import Pretty
93 # endif
94 import Bag      ( foldBag )
95
96 # if ! OMIT_NATIVE_CODEGEN
97 #  define IF_NCG(a) a
98 # else
99 #  define IF_NCG(a) {--}
100 # endif
101 #endif
102
103 -- SIGH: but we use unboxed "sizes"...
104 #if __GLASGOW_HASKELL__
105 #define IF_GHC(a,b) a
106 #else /* not GHC */
107 #define IF_GHC(a,b) b
108 #endif /* not GHC */
109
110
111 -- ---------------------------------------------------------------------------
112 -- The signature of the module
113
114 -- | An empty 'FiniteMap'.
115 emptyFM         :: FiniteMap key elt
116
117 -- | A 'FiniteMap' containing a single mapping
118 unitFM          :: key -> elt -> FiniteMap key elt
119
120 -- | Makes a 'FiniteMap' from a list of @(key,value)@ pairs. In the
121 -- case of duplicates, the last is taken
122 listToFM        :: (Ord key OUTPUTABLE_key) => [(key,elt)] -> FiniteMap key elt
123
124 #ifdef COMPILING_GHC
125 bagToFM         :: (Ord key OUTPUTABLE_key) => Bag (key,elt) -> FiniteMap key elt
126                         -- In the case of duplicates, who knows which is taken
127 #endif
128
129 --      ADDING AND DELETING
130
131 -- | Adds an element to a 'FiniteMap'.  Any previous mapping with the same
132 -- key is overwritten.
133 addToFM         :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> elt  -> FiniteMap key elt
134
135 -- | Adds a list of elements to a 'FiniteMap', in the order given in
136 -- the list.  Overwrites previous mappings.
137 addListToFM     :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> [(key,elt)] -> FiniteMap key elt
138
139                    -- Combines with previous binding
140                    -- In the combining function, the first argument is the "old" element,
141                    -- while the second is the "new" one.
142
143 -- | Adds an element to a 'FiniteMap'.  If there is already an element
144 -- with the same key, then the specified combination function is used
145 -- to calculate the new value. The already present element is passed as
146 -- the first argument and the new element to add as second.
147 addToFM_C       :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
148                            -> FiniteMap key elt -> key -> elt
149                            -> FiniteMap key elt
150
151 -- | A list version of 'addToFM_C'.  The elements are added in the
152 -- order given in the list.
153 addListToFM_C   :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
154                            -> FiniteMap key elt -> [(key,elt)]
155                            -> FiniteMap key elt
156
157 -- | Deletes an element from a 'FiniteMap'.  If there is no element with
158 -- the specified key, then the original 'FiniteMap' is returned.
159 delFromFM       :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key   -> FiniteMap key elt
160
161 -- | List version of 'delFromFM'.
162 delListFromFM   :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> [key] -> FiniteMap key elt
163
164 -- | Combine two 'FiniteMap's.  Mappings in the second argument shadow
165 -- those in the first.
166 plusFM          :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
167                            -> FiniteMap key elt
168
169 -- | Combine two 'FiniteMap's.  The specified combination function is
170 -- used to calculate the new value when there are two elements with
171 -- the same key.
172 plusFM_C        :: (Ord key OUTPUTABLE_key) => (elt -> elt -> elt)
173                            -> FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
174
175 -- | @(minusFM a1 a2)@ deletes from @a1@ any mappings which are bound in @a2@
176 minusFM         :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
177
178 -- | @(intersectFM a1 a2)@ returns a new 'FiniteMap' containing
179 -- mappings from @a1@ for which @a2@ also has a mapping with the same
180 -- key.
181 intersectFM     :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt -> FiniteMap key elt
182
183 -- | Returns the interesction of two mappings, using the specified
184 -- combination function to combine values.
185 intersectFM_C   :: (Ord key OUTPUTABLE_key) => (elt1 -> elt2 -> elt3)
186                            -> FiniteMap key elt1 -> FiniteMap key elt2 -> FiniteMap key elt3
187
188 --      MAPPING, FOLDING, FILTERING
189 foldFM          :: (key -> elt -> a -> a) -> a -> FiniteMap key elt -> a
190 mapFM           :: (key -> elt1 -> elt2) -> FiniteMap key elt1 -> FiniteMap key elt2
191 filterFM        :: (Ord key OUTPUTABLE_key) => (key -> elt -> Bool)
192                            -> FiniteMap key elt -> FiniteMap key elt
193
194 --      INTERROGATING
195 sizeFM          :: FiniteMap key elt -> Int
196 isEmptyFM       :: FiniteMap key elt -> Bool
197
198 -- | Returns 'True' if the specified @key@ has a mapping in this
199 -- 'FiniteMap', or 'False' otherwise.
200 elemFM          :: (Ord key OUTPUTABLE_key) => key -> FiniteMap key elt -> Bool
201
202 -- | Looks up a key in a 'FiniteMap', returning @'Just' v@ if the key
203 -- was found with value @v@, or 'Nothing' otherwise.
204 lookupFM        :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> Maybe elt
205
206 -- | Looks up a key in a 'FiniteMap', returning @elt@ if the specified
207 -- @key@ was not found.
208 lookupWithDefaultFM
209                 :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> elt -> key -> elt
210                 -- lookupWithDefaultFM supplies a "default" elt
211                 -- to return for an unmapped key
212
213 --      LISTIFYING
214
215 -- | Convert a 'FiniteMap' to a @[(key, elt)]@ sorted by 'Ord' key
216 --
217 fmToList        :: FiniteMap key elt -> [(key,elt)]
218
219 -- | Extract the keys from a 'FiniteMap', in the order of the keys, so
220 --
221 -- > keysFM == map fst . fmToList
222 --
223 keysFM          :: FiniteMap key elt -> [key]
224
225 -- | Extract the elements from a 'FiniteMap', in the order of the keys, so
226 --
227 -- > eltsFM == map snd . fmToList
228 --
229 eltsFM          :: FiniteMap key elt -> [elt]
230
231 -- ---------------------------------------------------------------------------
232 -- The @FiniteMap@ data type, and building of same
233
234 -- Invariants about @FiniteMap@:
235 --
236 -- *  all keys in a FiniteMap are distinct
237 --
238 -- * all keys in left  subtree are $<$ key in Branch and
239 --   all keys in right subtree are $>$ key in Branch
240 -- 
241 -- * size field of a Branch gives number of Branch nodes in the tree
242 -- 
243 -- * size of left subtree is differs from size of right subtree by a
244 --   factor of at most \tr{sIZE_RATIO}
245
246 -- | A mapping from @key@s to @elt@s.
247 data FiniteMap key elt
248   = EmptyFM
249   | Branch key elt              -- Key and elt stored here
250     IF_GHC(Int#,Int{-STRICT-})  -- Size >= 1
251     (FiniteMap key elt)         -- Children
252     (FiniteMap key elt)
253
254
255 emptyFM = EmptyFM
256 {-
257 emptyFM
258   = Branch bottom bottom IF_GHC(0#,0) bottom bottom
259   where
260     bottom = panic "emptyFM"
261 -}
262
263 --  #define EmptyFM (Branch _ _ IF_GHC(0#,0) _ _)
264
265 unitFM key elt = Branch key elt IF_GHC(1#,1) emptyFM emptyFM
266
267 listToFM = addListToFM emptyFM
268
269 #ifdef COMPILING_GHC
270 bagToFM = foldBag plusFM (\ (k,v) -> unitFM k v) emptyFM
271 #endif
272
273
274 -- ---------------------------------------------------------------------------
275 -- Adding to and deleting from @FiniteMaps@
276
277 addToFM fm key elt = addToFM_C (\ old new -> new) fm key elt
278
279 addToFM_C combiner EmptyFM key elt = unitFM key elt
280 addToFM_C combiner (Branch key elt size fm_l fm_r) new_key new_elt
281 #ifdef __GLASGOW_HASKELL__
282   = case _tagCmp new_key key of
283         _LT -> mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
284         _GT -> mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
285         _EQ -> Branch new_key (combiner elt new_elt) size fm_l fm_r
286 #else
287   | new_key < key = mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
288   | new_key > key = mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
289   | otherwise     = Branch new_key (combiner elt new_elt) size fm_l fm_r
290 #endif
291
292 addListToFM fm key_elt_pairs = addListToFM_C (\ old new -> new) fm key_elt_pairs
293
294 addListToFM_C combiner fm key_elt_pairs
295   = foldl add fm key_elt_pairs  -- foldl adds from the left
296   where
297     add fmap (key,elt) = addToFM_C combiner fmap key elt
298
299
300 delFromFM EmptyFM del_key = emptyFM
301 delFromFM (Branch key elt size fm_l fm_r) del_key
302 #if __GLASGOW_HASKELL__
303   = case _tagCmp del_key key of
304         _GT -> mkBalBranch key elt fm_l (delFromFM fm_r del_key)
305         _LT -> mkBalBranch key elt (delFromFM fm_l del_key) fm_r
306         _EQ -> glueBal fm_l fm_r
307 #else
308   | del_key > key
309   = mkBalBranch key elt fm_l (delFromFM fm_r del_key)
310
311   | del_key < key
312   = mkBalBranch key elt (delFromFM fm_l del_key) fm_r
313
314   | key == del_key
315   = glueBal fm_l fm_r
316 #endif
317
318 delListFromFM fm keys = foldl delFromFM fm keys
319
320 -- ---------------------------------------------------------------------------
321 -- Combining @FiniteMaps@
322
323 plusFM_C combiner EmptyFM fm2 = fm2
324 plusFM_C combiner fm1 EmptyFM = fm1
325 plusFM_C combiner fm1 (Branch split_key elt2 _ left right)
326   = mkVBalBranch split_key new_elt
327                  (plusFM_C combiner lts left)
328                  (plusFM_C combiner gts right)
329   where
330     lts     = splitLT fm1 split_key
331     gts     = splitGT fm1 split_key
332     new_elt = case lookupFM fm1 split_key of
333                 Nothing   -> elt2
334                 Just elt1 -> combiner elt1 elt2
335
336 -- It's worth doing plusFM specially, because we don't need
337 -- to do the lookup in fm1.
338
339 plusFM EmptyFM fm2 = fm2
340 plusFM fm1 EmptyFM = fm1
341 plusFM fm1 (Branch split_key elt1 _ left right)
342   = mkVBalBranch split_key elt1 (plusFM lts left) (plusFM gts right)
343   where
344     lts     = splitLT fm1 split_key
345     gts     = splitGT fm1 split_key
346
347 minusFM EmptyFM fm2 = emptyFM
348 minusFM fm1 EmptyFM = fm1
349 minusFM fm1 (Branch split_key elt _ left right)
350   = glueVBal (minusFM lts left) (minusFM gts right)
351         -- The two can be way different, so we need glueVBal
352   where
353     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
354     gts = splitGT fm1 split_key         -- are not in either.
355
356 intersectFM fm1 fm2 = intersectFM_C (\ left right -> right) fm1 fm2
357
358 intersectFM_C combiner fm1 EmptyFM = emptyFM
359 intersectFM_C combiner EmptyFM fm2 = emptyFM
360 intersectFM_C combiner fm1 (Branch split_key elt2 _ left right)
361
362   | isJust maybe_elt1   -- split_elt *is* in intersection
363   = mkVBalBranch split_key (combiner elt1 elt2) (intersectFM_C combiner lts left)
364                                                 (intersectFM_C combiner gts right)
365
366   | otherwise                   -- split_elt is *not* in intersection
367   = glueVBal (intersectFM_C combiner lts left) (intersectFM_C combiner gts right)
368
369   where
370     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
371     gts = splitGT fm1 split_key         -- are not in either.
372
373     maybe_elt1 = lookupFM fm1 split_key
374     Just elt1  = maybe_elt1
375
376
377 -- ---------------------------------------------------------------------------
378 -- Mapping, folding, and filtering with @FiniteMaps@
379
380 foldFM k z EmptyFM = z
381 foldFM k z (Branch key elt _ fm_l fm_r)
382   = foldFM k (k key elt (foldFM k z fm_r)) fm_l
383
384 mapFM f EmptyFM = emptyFM
385 mapFM f (Branch key elt size fm_l fm_r)
386   = Branch key (f key elt) size (mapFM f fm_l) (mapFM f fm_r)
387
388 filterFM p EmptyFM = emptyFM
389 filterFM p (Branch key elt _ fm_l fm_r)
390   | p key elt           -- Keep the item
391   = mkVBalBranch key elt (filterFM p fm_l) (filterFM p fm_r)
392
393   | otherwise           -- Drop the item
394   = glueVBal (filterFM p fm_l) (filterFM p fm_r)
395
396
397 -- ---------------------------------------------------------------------------
398 -- Interrogating @FiniteMaps@
399
400 --{-# INLINE sizeFM #-}
401 sizeFM EmptyFM               = 0
402 sizeFM (Branch _ _ size _ _) = IF_GHC(I# size, size)
403
404 isEmptyFM fm = sizeFM fm == 0
405
406 lookupFM EmptyFM key = Nothing
407 lookupFM (Branch key elt _ fm_l fm_r) key_to_find
408 #if __GLASGOW_HASKELL__
409   = case _tagCmp key_to_find key of
410         _LT -> lookupFM fm_l key_to_find
411         _GT -> lookupFM fm_r key_to_find
412         _EQ -> Just elt
413 #else
414   | key_to_find < key = lookupFM fm_l key_to_find
415   | key_to_find > key = lookupFM fm_r key_to_find
416   | otherwise     = Just elt
417 #endif
418
419 key `elemFM` fm
420   = case (lookupFM fm key) of { Nothing -> False; Just elt -> True }
421
422 lookupWithDefaultFM fm deflt key
423   = case (lookupFM fm key) of { Nothing -> deflt; Just elt -> elt }
424
425
426 -- ---------------------------------------------------------------------------
427 -- Listifying @FiniteMaps@
428
429 fmToList fm = foldFM (\ key elt rest -> (key,elt) : rest) [] fm
430 keysFM fm   = foldFM (\ key elt rest -> key : rest)       [] fm
431 eltsFM fm   = foldFM (\ key elt rest -> elt : rest)       [] fm
432
433
434 -- ---------------------------------------------------------------------------
435 -- Bulk operations on all keys >= a certain threshold
436
437 -- | Fold through all elements greater than or equal to the supplied key,
438 -- in increasing order.
439 foldFM_GE       :: Ord key => (key -> elt -> a -> a) -> a -> key ->
440    FiniteMap key elt -> a
441
442 foldFM_GE k z fr EmptyFM = z
443 foldFM_GE k z fr (Branch key elt _ fm_l fm_r)
444   | key >= fr = foldFM_GE k (k key elt (foldFM_GE k z fr fm_r)) fr fm_l
445   | otherwise = foldFM_GE k z fr fm_r
446
447 -- | List elements greater than or equal to the supplied key, in increasing
448 -- order
449 fmToList_GE      :: Ord key => FiniteMap key elt -> key ->  [(key,elt)]
450 fmToList_GE fm fr = foldFM_GE (\ key elt rest -> (key,elt) : rest) [] fr fm
451
452 -- | List keys greater than or equal to the supplied key, in increasing order
453 keysFM_GE       :: Ord key => FiniteMap key elt -> key -> [key]
454 keysFM_GE fm fr  = foldFM_GE (\ key elt rest -> key : rest)       [] fr fm
455
456 -- | List elements corresponding to keys greater than or equal to the supplied
457 -- key, in increasing order of key.
458 eltsFM_GE       :: Ord key => FiniteMap key elt -> key -> [elt]
459 eltsFM_GE fm fr  = foldFM_GE (\ key elt rest -> elt : rest)       [] fr fm
460
461 -- ---------------------------------------------------------------------------
462 -- The implementation of balancing
463
464 -- Basic construction of a @FiniteMap@:
465
466 -- @mkBranch@ simply gets the size component right.  This is the ONLY
467 -- (non-trivial) place the Branch object is built, so the ASSERTion
468 -- recursively checks consistency.  (The trivial use of Branch is in
469 -- @unitFM@.)
470
471 sIZE_RATIO :: Int
472 sIZE_RATIO = 5
473
474 mkBranch :: (Ord key OUTPUTABLE_key)            -- Used for the assertion checking only
475          => Int
476          -> key -> elt
477          -> FiniteMap key elt -> FiniteMap key elt
478          -> FiniteMap key elt
479
480 mkBranch which key elt fm_l fm_r
481   = --ASSERT( left_ok && right_ok && balance_ok )
482 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
483     if not ( left_ok && right_ok && balance_ok ) then
484         pprPanic ("mkBranch:"++show which) (ppAboves [ppr PprDebug [left_ok, right_ok, balance_ok],
485                                        ppr PprDebug key,
486                                        ppr PprDebug fm_l,
487                                        ppr PprDebug fm_r])
488     else
489 #endif
490     let
491         result = Branch key elt (unbox (1 + left_size + right_size)) fm_l fm_r
492     in
493 --    if sizeFM result <= 8 then
494         result
495 --    else
496 --      pprTrace ("mkBranch:"++(show which)) (ppr PprDebug result) (
497 --      result
498 --      )
499   where
500     left_ok  = case fm_l of
501                 EmptyFM                  -> True
502                 Branch left_key _ _ _ _  -> let
503                                                 biggest_left_key = fst (findMax fm_l)
504                                             in
505                                             biggest_left_key < key
506     right_ok = case fm_r of
507                 EmptyFM                  -> True
508                 Branch right_key _ _ _ _ -> let
509                                                 smallest_right_key = fst (findMin fm_r)
510                                             in
511                                             key < smallest_right_key
512     balance_ok = True -- sigh
513 {- LATER:
514     balance_ok
515       = -- Both subtrees have one or no elements...
516         (left_size + right_size <= 1)
517 -- NO         || left_size == 0  -- ???
518 -- NO         || right_size == 0 -- ???
519         -- ... or the number of elements in a subtree does not exceed
520         -- sIZE_RATIO times the number of elements in the other subtree
521       || (left_size  * sIZE_RATIO >= right_size &&
522           right_size * sIZE_RATIO >= left_size)
523 -}
524
525     left_size  = sizeFM fm_l
526     right_size = sizeFM fm_r
527
528 #if __GLASGOW_HASKELL__
529     unbox :: Int -> Int#
530     unbox (I# size) = size
531 #else
532     unbox :: Int -> Int
533     unbox x = x
534 #endif
535
536
537 -- ---------------------------------------------------------------------------
538 -- {\em Balanced} construction of a @FiniteMap@
539
540 -- @mkBalBranch@ rebalances, assuming that the subtrees aren't too far
541 -- out of whack.
542
543 mkBalBranch :: (Ord key OUTPUTABLE_key)
544             => key -> elt
545             -> FiniteMap key elt -> FiniteMap key elt
546             -> FiniteMap key elt
547
548 mkBalBranch key elt fm_L fm_R
549
550   | size_l + size_r < 2
551   = mkBranch 1{-which-} key elt fm_L fm_R
552
553   | size_r > sIZE_RATIO * size_l        -- Right tree too big
554   = case fm_R of
555         Branch _ _ _ fm_rl fm_rr
556                 | sizeFM fm_rl < 2 * sizeFM fm_rr -> single_L fm_L fm_R
557                 | otherwise                       -> double_L fm_L fm_R
558         -- Other case impossible
559
560   | size_l > sIZE_RATIO * size_r        -- Left tree too big
561   = case fm_L of
562         Branch _ _ _ fm_ll fm_lr
563                 | sizeFM fm_lr < 2 * sizeFM fm_ll -> single_R fm_L fm_R
564                 | otherwise                       -> double_R fm_L fm_R
565         -- Other case impossible
566
567   | otherwise                           -- No imbalance
568   = mkBranch 2{-which-} key elt fm_L fm_R
569
570   where
571     size_l   = sizeFM fm_L
572     size_r   = sizeFM fm_R
573
574     single_L fm_l (Branch key_r elt_r _ fm_rl fm_rr)
575         = mkBranch 3{-which-} key_r elt_r (mkBranch 4{-which-} key elt fm_l fm_rl) fm_rr
576
577     double_L fm_l (Branch key_r elt_r _ (Branch key_rl elt_rl _ fm_rll fm_rlr) fm_rr)
578         = mkBranch 5{-which-} key_rl elt_rl (mkBranch 6{-which-} key   elt   fm_l   fm_rll)
579                                  (mkBranch 7{-which-} key_r elt_r fm_rlr fm_rr)
580
581     single_R (Branch key_l elt_l _ fm_ll fm_lr) fm_r
582         = mkBranch 8{-which-} key_l elt_l fm_ll (mkBranch 9{-which-} key elt fm_lr fm_r)
583
584     double_R (Branch key_l elt_l _ fm_ll (Branch key_lr elt_lr _ fm_lrl fm_lrr)) fm_r
585         = mkBranch 10{-which-} key_lr elt_lr (mkBranch 11{-which-} key_l elt_l fm_ll  fm_lrl)
586                                  (mkBranch 12{-which-} key   elt   fm_lrr fm_r)
587
588
589 mkVBalBranch :: (Ord key OUTPUTABLE_key)
590              => key -> elt
591              -> FiniteMap key elt -> FiniteMap key elt
592              -> FiniteMap key elt
593
594 -- Assert: in any call to (mkVBalBranch_C comb key elt l r),
595 --         (a) all keys in l are < all keys in r
596 --         (b) all keys in l are < key
597 --         (c) all keys in r are > key
598
599 mkVBalBranch key elt EmptyFM fm_r = addToFM fm_r key elt
600 mkVBalBranch key elt fm_l EmptyFM = addToFM fm_l key elt
601
602 mkVBalBranch key elt fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
603                      fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
604   | sIZE_RATIO * size_l < size_r
605   = mkBalBranch key_r elt_r (mkVBalBranch key elt fm_l fm_rl) fm_rr
606
607   | sIZE_RATIO * size_r < size_l
608   = mkBalBranch key_l elt_l fm_ll (mkVBalBranch key elt fm_lr fm_r)
609
610   | otherwise
611   = mkBranch 13{-which-} key elt fm_l fm_r
612
613   where
614     size_l = sizeFM fm_l
615     size_r = sizeFM fm_r
616
617 -- ---------------------------------------------------------------------------
618 -- Gluing two trees together
619
620 -- @glueBal@ assumes its two arguments aren't too far out of whack, just
621 -- like @mkBalBranch@.  But: all keys in first arg are $<$ all keys in
622 -- second.
623
624 glueBal :: (Ord key OUTPUTABLE_key)
625         => FiniteMap key elt -> FiniteMap key elt
626         -> FiniteMap key elt
627
628 glueBal EmptyFM fm2 = fm2
629 glueBal fm1 EmptyFM = fm1
630 glueBal fm1 fm2
631         -- The case analysis here (absent in Adams' program) is really to deal
632         -- with the case where fm2 is a singleton. Then deleting the minimum means
633         -- we pass an empty tree to mkBalBranch, which breaks its invariant.
634   | sizeFM fm2 > sizeFM fm1
635   = mkBalBranch mid_key2 mid_elt2 fm1 (deleteMin fm2)
636
637   | otherwise
638   = mkBalBranch mid_key1 mid_elt1 (deleteMax fm1) fm2
639   where
640     (mid_key1, mid_elt1) = findMax fm1
641     (mid_key2, mid_elt2) = findMin fm2
642
643 -- @glueVBal@ copes with arguments which can be of any size.
644 -- But: all keys in first arg are $<$ all keys in second.
645
646 glueVBal :: (Ord key OUTPUTABLE_key)
647          => FiniteMap key elt -> FiniteMap key elt
648          -> FiniteMap key elt
649
650 glueVBal EmptyFM fm2 = fm2
651 glueVBal fm1 EmptyFM = fm1
652 glueVBal fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
653          fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
654   | sIZE_RATIO * size_l < size_r
655   = mkBalBranch key_r elt_r (glueVBal fm_l fm_rl) fm_rr
656
657   | sIZE_RATIO * size_r < size_l
658   = mkBalBranch key_l elt_l fm_ll (glueVBal fm_lr fm_r)
659
660   | otherwise           -- We now need the same two cases as in glueBal above.
661   = glueBal fm_l fm_r
662   where
663     size_l = sizeFM fm_l
664     size_r = sizeFM fm_r
665
666
667 -- ---------------------------------------------------------------------------
668 -- Local utilities
669
670 splitLT, splitGT :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> FiniteMap key elt
671
672 -- splitLT fm split_key  =  fm restricted to keys <  split_key
673 -- splitGT fm split_key  =  fm restricted to keys >  split_key
674
675 splitLT EmptyFM split_key = emptyFM
676 splitLT (Branch key elt _ fm_l fm_r) split_key
677 #if __GLASGOW_HASKELL__
678   = case _tagCmp split_key key of
679         _LT -> splitLT fm_l split_key
680         _GT -> mkVBalBranch key elt fm_l (splitLT fm_r split_key)
681         _EQ -> fm_l
682 #else
683   | split_key < key = splitLT fm_l split_key
684   | split_key > key = mkVBalBranch key elt fm_l (splitLT fm_r split_key)
685   | otherwise       = fm_l
686 #endif
687
688 splitGT EmptyFM split_key = emptyFM
689 splitGT (Branch key elt _ fm_l fm_r) split_key
690 #if __GLASGOW_HASKELL__
691   = case _tagCmp split_key key of
692         _GT -> splitGT fm_r split_key
693         _LT -> mkVBalBranch key elt (splitGT fm_l split_key) fm_r
694         _EQ -> fm_r
695 #else
696   | split_key > key = splitGT fm_r split_key
697   | split_key < key = mkVBalBranch key elt (splitGT fm_l split_key) fm_r
698   | otherwise       = fm_r
699 #endif
700
701 findMin :: FiniteMap key elt -> (key,elt)
702 findMin (Branch key elt _ EmptyFM _) = (key,elt)
703 findMin (Branch key elt _ fm_l    _) = findMin fm_l
704
705 deleteMin :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
706 deleteMin (Branch key elt _ EmptyFM fm_r) = fm_r
707 deleteMin (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt (deleteMin fm_l) fm_r
708
709 findMax :: FiniteMap key elt -> (key,elt)
710 findMax (Branch key elt _ _ EmptyFM) = (key,elt)
711 findMax (Branch key elt _ _    fm_r) = findMax fm_r
712
713 deleteMax :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
714 deleteMax (Branch key elt _ fm_l EmptyFM) = fm_l
715 deleteMax (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt fm_l (deleteMax fm_r)
716
717
718 -- ---------------------------------------------------------------------------
719 -- Output-ery
720
721 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
722
723 instance (Outputable key) => Outputable (FiniteMap key elt) where
724     ppr sty fm = pprX sty fm
725
726 pprX sty EmptyFM = ppChar '!'
727 pprX sty (Branch key elt sz fm_l fm_r)
728  = ppBesides [ppLparen, pprX sty fm_l, ppSP,
729               ppr sty key, ppSP, ppInt (IF_GHC(I# sz, sz)), ppSP,
730               pprX sty fm_r, ppRparen]
731 #endif
732
733 #ifndef COMPILING_GHC
734 instance (Eq key, Eq elt) => Eq (FiniteMap key elt) where
735   fm_1 == fm_2 = (sizeFM   fm_1 == sizeFM   fm_2) &&   -- quick test
736                  (fmToList fm_1 == fmToList fm_2)
737
738 {- NO: not clear what The Right Thing to do is:
739 instance (Ord key, Ord elt) => Ord (FiniteMap key elt) where
740   fm_1 <= fm_2 = (sizeFM   fm_1 <= sizeFM   fm_2) &&   -- quick test
741                  (fmToList fm_1 <= fmToList fm_2)
742 -}
743 #endif
744
745 -- ---------------------------------------------------------------------------
746 -- Efficiency pragmas for GHC
747
748 -- When the FiniteMap module is used in GHC, we specialise it for
749 -- \tr{Uniques}, for dastardly efficiency reasons.
750
751 #if defined(COMPILING_GHC) && __GLASGOW_HASKELL__ && !defined(REALLY_HASKELL_1_3)
752
753 {-# SPECIALIZE addListToFM
754                 :: FiniteMap (FAST_STRING, FAST_STRING) elt -> [((FAST_STRING, FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
755                  , FiniteMap RdrName elt -> [(RdrName,elt)] -> FiniteMap RdrName elt
756     IF_NCG(COMMA   FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
757     #-}
758 {-# SPECIALIZE addListToFM_C
759                 :: (elt -> elt -> elt) -> FiniteMap TyCon elt -> [(TyCon,elt)] -> FiniteMap TyCon elt
760                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
761     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
762     #-}
763 {-# SPECIALIZE addToFM
764                 :: FiniteMap CLabel elt -> CLabel -> elt  -> FiniteMap CLabel elt
765                  , FiniteMap FAST_STRING elt -> FAST_STRING -> elt  -> FiniteMap FAST_STRING elt
766                  , FiniteMap (FAST_STRING, FAST_STRING) elt -> (FAST_STRING, FAST_STRING) -> elt  -> FiniteMap (FAST_STRING, FAST_STRING) elt
767                  , FiniteMap RdrName elt -> RdrName -> elt  -> FiniteMap RdrName elt
768                  , FiniteMap OrigName elt -> OrigName -> elt  -> FiniteMap OrigName elt
769     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> elt  -> FiniteMap Reg elt)
770     #-}
771 {-# SPECIALIZE addToFM_C
772                 :: (elt -> elt -> elt) -> FiniteMap (RdrName, RdrName) elt -> (RdrName, RdrName) -> elt -> FiniteMap (RdrName, RdrName) elt
773                  , (elt -> elt -> elt) -> FiniteMap (OrigName, OrigName) elt -> (OrigName, OrigName) -> elt -> FiniteMap (OrigName, OrigName) elt
774                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FAST_STRING -> elt -> FiniteMap FAST_STRING elt
775     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> Reg -> elt -> FiniteMap Reg elt)
776     #-}
777 {-# SPECIALIZE bagToFM
778                 :: Bag (FAST_STRING,elt) -> FiniteMap FAST_STRING elt
779     #-}
780 {-# SPECIALIZE delListFromFM
781                 :: FiniteMap RdrName elt -> [RdrName]   -> FiniteMap RdrName elt
782                  , FiniteMap OrigName elt -> [OrigName]   -> FiniteMap OrigName elt
783                  , FiniteMap FAST_STRING elt -> [FAST_STRING]   -> FiniteMap FAST_STRING elt
784     IF_NCG(COMMA   FiniteMap Reg elt -> [Reg]   -> FiniteMap Reg elt)
785     #-}
786 {-# SPECIALIZE listToFM
787                 :: [([Char],elt)] -> FiniteMap [Char] elt
788                  , [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
789                  , [((FAST_STRING,FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
790                  , [(OrigName,elt)] -> FiniteMap OrigName elt
791     IF_NCG(COMMA   [(Reg COMMA elt)] -> FiniteMap Reg elt)
792     #-}
793 {-# SPECIALIZE lookupFM
794                 :: FiniteMap CLabel elt -> CLabel -> Maybe elt
795                  , FiniteMap [Char] elt -> [Char] -> Maybe elt
796                  , FiniteMap FAST_STRING elt -> FAST_STRING -> Maybe elt
797                  , FiniteMap (FAST_STRING,FAST_STRING) elt -> (FAST_STRING,FAST_STRING) -> Maybe elt
798                  , FiniteMap OrigName elt -> OrigName -> Maybe elt
799                  , FiniteMap (OrigName,OrigName) elt -> (OrigName,OrigName) -> Maybe elt
800                  , FiniteMap RdrName elt -> RdrName -> Maybe elt
801                  , FiniteMap (RdrName,RdrName) elt -> (RdrName,RdrName) -> Maybe elt
802     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> Maybe elt)
803     #-}
804 {-# SPECIALIZE lookupWithDefaultFM
805                 :: FiniteMap FAST_STRING elt -> elt -> FAST_STRING -> elt
806     IF_NCG(COMMA   FiniteMap Reg elt -> elt -> Reg -> elt)
807     #-}
808 {-# SPECIALIZE plusFM
809                 :: FiniteMap RdrName elt -> FiniteMap RdrName elt -> FiniteMap RdrName elt
810                  , FiniteMap OrigName elt -> FiniteMap OrigName elt -> FiniteMap OrigName elt
811                  , FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
812     IF_NCG(COMMA   FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
813     #-}
814 {-# SPECIALIZE plusFM_C
815                 :: (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
816     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
817     #-}
818
819 #endif /* compiling for GHC */