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