[project @ 2003-11-06 12:50:22 by ross]
[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 elt -> FiniteMap key elt -> FiniteMap key elt
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 interesction 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
281 -- ---------------------------------------------------------------------------
282 -- Adding to and deleting from @FiniteMaps@
283
284 addToFM fm key elt = addToFM_C (\ old new -> new) fm key elt
285
286 addToFM_C combiner EmptyFM key elt = unitFM key elt
287 addToFM_C combiner (Branch key elt size fm_l fm_r) new_key new_elt
288 #ifdef __GLASGOW_HASKELL__
289   = case _tagCmp new_key key of
290         _LT -> mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
291         _GT -> mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
292         _EQ -> Branch new_key (combiner elt new_elt) size fm_l fm_r
293 #else
294   | new_key < key = mkBalBranch key elt (addToFM_C combiner fm_l new_key new_elt) fm_r
295   | new_key > key = mkBalBranch key elt fm_l (addToFM_C combiner fm_r new_key new_elt)
296   | otherwise     = Branch new_key (combiner elt new_elt) size fm_l fm_r
297 #endif
298
299 addListToFM fm key_elt_pairs = addListToFM_C (\ old new -> new) fm key_elt_pairs
300
301 addListToFM_C combiner fm key_elt_pairs
302   = foldl add fm key_elt_pairs  -- foldl adds from the left
303   where
304     add fmap (key,elt) = addToFM_C combiner fmap key elt
305
306
307 delFromFM EmptyFM del_key = emptyFM
308 delFromFM (Branch key elt size fm_l fm_r) del_key
309 #if __GLASGOW_HASKELL__
310   = case _tagCmp del_key key of
311         _GT -> mkBalBranch key elt fm_l (delFromFM fm_r del_key)
312         _LT -> mkBalBranch key elt (delFromFM fm_l del_key) fm_r
313         _EQ -> glueBal fm_l fm_r
314 #else
315   | del_key > key
316   = mkBalBranch key elt fm_l (delFromFM fm_r del_key)
317
318   | del_key < key
319   = mkBalBranch key elt (delFromFM fm_l del_key) fm_r
320
321   | key == del_key
322   = glueBal fm_l fm_r
323 #endif
324
325 delListFromFM fm keys = foldl delFromFM fm keys
326
327 -- ---------------------------------------------------------------------------
328 -- Combining @FiniteMaps@
329
330 plusFM_C combiner EmptyFM fm2 = fm2
331 plusFM_C combiner fm1 EmptyFM = fm1
332 plusFM_C combiner fm1 (Branch split_key elt2 _ left right)
333   = mkVBalBranch split_key new_elt
334                  (plusFM_C combiner lts left)
335                  (plusFM_C combiner gts right)
336   where
337     lts     = splitLT fm1 split_key
338     gts     = splitGT fm1 split_key
339     new_elt = case lookupFM fm1 split_key of
340                 Nothing   -> elt2
341                 Just elt1 -> combiner elt1 elt2
342
343 -- It's worth doing plusFM specially, because we don't need
344 -- to do the lookup in fm1.
345
346 plusFM EmptyFM fm2 = fm2
347 plusFM fm1 EmptyFM = fm1
348 plusFM fm1 (Branch split_key elt1 _ left right)
349   = mkVBalBranch split_key elt1 (plusFM lts left) (plusFM gts right)
350   where
351     lts     = splitLT fm1 split_key
352     gts     = splitGT fm1 split_key
353
354 minusFM EmptyFM fm2 = emptyFM
355 minusFM fm1 EmptyFM = fm1
356 minusFM fm1 (Branch split_key elt _ left right)
357   = glueVBal (minusFM lts left) (minusFM gts right)
358         -- The two can be way different, so we need glueVBal
359   where
360     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
361     gts = splitGT fm1 split_key         -- are not in either.
362
363 intersectFM fm1 fm2 = intersectFM_C (\ left right -> right) fm1 fm2
364
365 intersectFM_C combiner fm1 EmptyFM = emptyFM
366 intersectFM_C combiner EmptyFM fm2 = emptyFM
367 intersectFM_C combiner fm1 (Branch split_key elt2 _ left right)
368
369   | isJust maybe_elt1   -- split_elt *is* in intersection
370   = mkVBalBranch split_key (combiner elt1 elt2) (intersectFM_C combiner lts left)
371                                                 (intersectFM_C combiner gts right)
372
373   | otherwise                   -- split_elt is *not* in intersection
374   = glueVBal (intersectFM_C combiner lts left) (intersectFM_C combiner gts right)
375
376   where
377     lts = splitLT fm1 split_key         -- NB gt and lt, so the equal ones
378     gts = splitGT fm1 split_key         -- are not in either.
379
380     maybe_elt1 = lookupFM fm1 split_key
381     Just elt1  = maybe_elt1
382
383
384 -- ---------------------------------------------------------------------------
385 -- Mapping, folding, and filtering with @FiniteMaps@
386
387 foldFM k z EmptyFM = z
388 foldFM k z (Branch key elt _ fm_l fm_r)
389   = foldFM k (k key elt (foldFM k z fm_r)) fm_l
390
391 mapFM f EmptyFM = emptyFM
392 mapFM f (Branch key elt size fm_l fm_r)
393   = Branch key (f key elt) size (mapFM f fm_l) (mapFM f fm_r)
394
395 filterFM p EmptyFM = emptyFM
396 filterFM p (Branch key elt _ fm_l fm_r)
397   | p key elt           -- Keep the item
398   = mkVBalBranch key elt (filterFM p fm_l) (filterFM p fm_r)
399
400   | otherwise           -- Drop the item
401   = glueVBal (filterFM p fm_l) (filterFM p fm_r)
402
403
404 -- ---------------------------------------------------------------------------
405 -- Interrogating @FiniteMaps@
406
407 --{-# INLINE sizeFM #-}
408 sizeFM EmptyFM               = 0
409 sizeFM (Branch _ _ size _ _) = IF_GHC(I# size, size)
410
411 isEmptyFM fm = sizeFM fm == 0
412
413 lookupFM EmptyFM key = Nothing
414 lookupFM (Branch key elt _ fm_l fm_r) key_to_find
415 #if __GLASGOW_HASKELL__
416   = case _tagCmp key_to_find key of
417         _LT -> lookupFM fm_l key_to_find
418         _GT -> lookupFM fm_r key_to_find
419         _EQ -> Just elt
420 #else
421   | key_to_find < key = lookupFM fm_l key_to_find
422   | key_to_find > key = lookupFM fm_r key_to_find
423   | otherwise     = Just elt
424 #endif
425
426 key `elemFM` fm
427   = case (lookupFM fm key) of { Nothing -> False; Just elt -> True }
428
429 lookupWithDefaultFM fm deflt key
430   = case (lookupFM fm key) of { Nothing -> deflt; Just elt -> elt }
431
432
433 -- ---------------------------------------------------------------------------
434 -- Listifying @FiniteMaps@
435
436 fmToList fm = foldFM (\ key elt rest -> (key,elt) : rest) [] fm
437 keysFM fm   = foldFM (\ key elt rest -> key : rest)       [] fm
438 eltsFM fm   = foldFM (\ key elt rest -> elt : rest)       [] fm
439
440
441 -- ---------------------------------------------------------------------------
442 -- Bulk operations on all keys >= or <= a certain threshold
443
444 -- | Fold through all elements greater than or equal to the supplied key,
445 -- in increasing order.
446 foldFM_GE       :: Ord key => (key -> elt -> a -> a) -> a -> key ->
447    FiniteMap key elt -> a
448
449 foldFM_GE k z fr EmptyFM = z
450 foldFM_GE k z fr (Branch key elt _ fm_l fm_r)
451   | key >= fr = foldFM_GE k (k key elt (foldFM_GE k z fr fm_r)) fr fm_l
452   | otherwise = foldFM_GE k z fr fm_r
453
454 -- | List elements greater than or equal to the supplied key, in increasing
455 -- order
456 fmToList_GE      :: Ord key => FiniteMap key elt -> key ->  [(key,elt)]
457 fmToList_GE fm fr = foldFM_GE (\ key elt rest -> (key,elt) : rest) [] fr fm
458
459 -- | List keys greater than or equal to the supplied key, in increasing order
460 keysFM_GE       :: Ord key => FiniteMap key elt -> key -> [key]
461 keysFM_GE fm fr  = foldFM_GE (\ key elt rest -> key : rest)       [] fr fm
462
463 -- | List elements corresponding to keys greater than or equal to the supplied
464 -- key, in increasing order of key.
465 eltsFM_GE       :: Ord key => FiniteMap key elt -> key -> [elt]
466 eltsFM_GE fm fr  = foldFM_GE (\ key elt rest -> elt : rest)       [] fr fm
467
468 -- | Fold through all elements less than or equal to the supplied key,
469 -- in decreasing order.
470 foldFM_LE       :: Ord key => (key -> elt -> a -> a) -> a -> key ->
471    FiniteMap key elt -> a
472 foldFM_LE k z fr EmptyFM = z
473 foldFM_LE k z fr (Branch key elt _ fm_l fm_r)
474   | key <= fr = foldFM_LE k (k key elt (foldFM_LE k z fr fm_l)) fr fm_r
475   | otherwise = foldFM_LE k z fr fm_l
476
477 -- | List elements greater than or equal to the supplied key, in decreasing
478 -- order
479 fmToList_LE      :: Ord key => FiniteMap key elt -> key ->  [(key,elt)]
480 fmToList_LE fm fr = foldFM_LE (\ key elt rest -> (key,elt) : rest) [] fr fm
481
482 -- | List keys greater than or equal to the supplied key, in decreasing order
483 keysFM_LE       :: Ord key => FiniteMap key elt -> key -> [key]
484 keysFM_LE fm fr  = foldFM_LE (\ key elt rest -> key : rest)       [] fr fm
485
486 -- | List elements corresponding to keys greater than or equal to the supplied
487 -- key, in decreasing order of key.
488 eltsFM_LE       :: Ord key => FiniteMap key elt -> key -> [elt]
489 eltsFM_LE fm fr  = foldFM_LE (\ key elt rest -> elt : rest)       [] fr fm
490
491 -- ---------------------------------------------------------------------------
492 -- Getting minimum and maximum key out.
493 -- ---------------------------------------------------------------------------
494
495 -- | Extract minimum key, or Nothing if the map is empty.
496 minFM :: Ord key => FiniteMap key elt -> Maybe key
497 minFM EmptyFM = Nothing
498 minFM (Branch key _ _ fm_l _) =
499    case minFM fm_l of
500       Nothing -> Just key
501       Just key1 -> Just key1
502
503 -- | Extract maximum key, or Nothing if the map is empty.
504 maxFM :: Ord key => FiniteMap key elt -> Maybe key
505 maxFM EmptyFM = Nothing
506 maxFM (Branch key _ _ _ fm_r) =
507    case maxFM fm_r of
508       Nothing -> Just key
509       Just key1 -> Just key1
510
511
512 -- ---------------------------------------------------------------------------
513 -- The implementation of balancing
514
515 -- Basic construction of a @FiniteMap@:
516
517 -- @mkBranch@ simply gets the size component right.  This is the ONLY
518 -- (non-trivial) place the Branch object is built, so the ASSERTion
519 -- recursively checks consistency.  (The trivial use of Branch is in
520 -- @unitFM@.)
521
522 sIZE_RATIO :: Int
523 sIZE_RATIO = 5
524
525 mkBranch :: (Ord key OUTPUTABLE_key)            -- Used for the assertion checking only
526          => Int
527          -> key -> elt
528          -> FiniteMap key elt -> FiniteMap key elt
529          -> FiniteMap key elt
530
531 mkBranch which key elt fm_l fm_r
532   = --ASSERT( left_ok && right_ok && balance_ok )
533 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
534     if not ( left_ok && right_ok && balance_ok ) then
535         pprPanic ("mkBranch:"++show which) (ppAboves [ppr PprDebug [left_ok, right_ok, balance_ok],
536                                        ppr PprDebug key,
537                                        ppr PprDebug fm_l,
538                                        ppr PprDebug fm_r])
539     else
540 #endif
541     let
542         result = Branch key elt (unbox (1 + left_size + right_size)) fm_l fm_r
543     in
544 --    if sizeFM result <= 8 then
545         result
546 --    else
547 --      pprTrace ("mkBranch:"++(show which)) (ppr PprDebug result) (
548 --      result
549 --      )
550   where
551     left_ok  = case fm_l of
552                 EmptyFM                  -> True
553                 Branch left_key _ _ _ _  -> let
554                                                 biggest_left_key = fst (findMax fm_l)
555                                             in
556                                             biggest_left_key < key
557     right_ok = case fm_r of
558                 EmptyFM                  -> True
559                 Branch right_key _ _ _ _ -> let
560                                                 smallest_right_key = fst (findMin fm_r)
561                                             in
562                                             key < smallest_right_key
563     balance_ok = True -- sigh
564 {- LATER:
565     balance_ok
566       = -- Both subtrees have one or no elements...
567         (left_size + right_size <= 1)
568 -- NO         || left_size == 0  -- ???
569 -- NO         || right_size == 0 -- ???
570         -- ... or the number of elements in a subtree does not exceed
571         -- sIZE_RATIO times the number of elements in the other subtree
572       || (left_size  * sIZE_RATIO >= right_size &&
573           right_size * sIZE_RATIO >= left_size)
574 -}
575
576     left_size  = sizeFM fm_l
577     right_size = sizeFM fm_r
578
579 #if __GLASGOW_HASKELL__
580     unbox :: Int -> Int#
581     unbox (I# size) = size
582 #else
583     unbox :: Int -> Int
584     unbox x = x
585 #endif
586
587
588 -- ---------------------------------------------------------------------------
589 -- {\em Balanced} construction of a @FiniteMap@
590
591 -- @mkBalBranch@ rebalances, assuming that the subtrees aren't too far
592 -- out of whack.
593
594 mkBalBranch :: (Ord key OUTPUTABLE_key)
595             => key -> elt
596             -> FiniteMap key elt -> FiniteMap key elt
597             -> FiniteMap key elt
598
599 mkBalBranch key elt fm_L fm_R
600
601   | size_l + size_r < 2
602   = mkBranch 1{-which-} key elt fm_L fm_R
603
604   | size_r > sIZE_RATIO * size_l        -- Right tree too big
605   = case fm_R of
606         Branch _ _ _ fm_rl fm_rr
607                 | sizeFM fm_rl < 2 * sizeFM fm_rr -> single_L fm_L fm_R
608                 | otherwise                       -> double_L fm_L fm_R
609         -- Other case impossible
610
611   | size_l > sIZE_RATIO * size_r        -- Left tree too big
612   = case fm_L of
613         Branch _ _ _ fm_ll fm_lr
614                 | sizeFM fm_lr < 2 * sizeFM fm_ll -> single_R fm_L fm_R
615                 | otherwise                       -> double_R fm_L fm_R
616         -- Other case impossible
617
618   | otherwise                           -- No imbalance
619   = mkBranch 2{-which-} key elt fm_L fm_R
620
621   where
622     size_l   = sizeFM fm_L
623     size_r   = sizeFM fm_R
624
625     single_L fm_l (Branch key_r elt_r _ fm_rl fm_rr)
626         = mkBranch 3{-which-} key_r elt_r (mkBranch 4{-which-} key elt fm_l fm_rl) fm_rr
627
628     double_L fm_l (Branch key_r elt_r _ (Branch key_rl elt_rl _ fm_rll fm_rlr) fm_rr)
629         = mkBranch 5{-which-} key_rl elt_rl (mkBranch 6{-which-} key   elt   fm_l   fm_rll)
630                                  (mkBranch 7{-which-} key_r elt_r fm_rlr fm_rr)
631
632     single_R (Branch key_l elt_l _ fm_ll fm_lr) fm_r
633         = mkBranch 8{-which-} key_l elt_l fm_ll (mkBranch 9{-which-} key elt fm_lr fm_r)
634
635     double_R (Branch key_l elt_l _ fm_ll (Branch key_lr elt_lr _ fm_lrl fm_lrr)) fm_r
636         = mkBranch 10{-which-} key_lr elt_lr (mkBranch 11{-which-} key_l elt_l fm_ll  fm_lrl)
637                                  (mkBranch 12{-which-} key   elt   fm_lrr fm_r)
638
639
640 mkVBalBranch :: (Ord key OUTPUTABLE_key)
641              => key -> elt
642              -> FiniteMap key elt -> FiniteMap key elt
643              -> FiniteMap key elt
644
645 -- Assert: in any call to (mkVBalBranch_C comb key elt l r),
646 --         (a) all keys in l are < all keys in r
647 --         (b) all keys in l are < key
648 --         (c) all keys in r are > key
649
650 mkVBalBranch key elt EmptyFM fm_r = addToFM fm_r key elt
651 mkVBalBranch key elt fm_l EmptyFM = addToFM fm_l key elt
652
653 mkVBalBranch key elt fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
654                      fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
655   | sIZE_RATIO * size_l < size_r
656   = mkBalBranch key_r elt_r (mkVBalBranch key elt fm_l fm_rl) fm_rr
657
658   | sIZE_RATIO * size_r < size_l
659   = mkBalBranch key_l elt_l fm_ll (mkVBalBranch key elt fm_lr fm_r)
660
661   | otherwise
662   = mkBranch 13{-which-} key elt fm_l fm_r
663
664   where
665     size_l = sizeFM fm_l
666     size_r = sizeFM fm_r
667
668 -- ---------------------------------------------------------------------------
669 -- Gluing two trees together
670
671 -- @glueBal@ assumes its two arguments aren't too far out of whack, just
672 -- like @mkBalBranch@.  But: all keys in first arg are $<$ all keys in
673 -- second.
674
675 glueBal :: (Ord key OUTPUTABLE_key)
676         => FiniteMap key elt -> FiniteMap key elt
677         -> FiniteMap key elt
678
679 glueBal EmptyFM fm2 = fm2
680 glueBal fm1 EmptyFM = fm1
681 glueBal fm1 fm2
682         -- The case analysis here (absent in Adams' program) is really to deal
683         -- with the case where fm2 is a singleton. Then deleting the minimum means
684         -- we pass an empty tree to mkBalBranch, which breaks its invariant.
685   | sizeFM fm2 > sizeFM fm1
686   = mkBalBranch mid_key2 mid_elt2 fm1 (deleteMin fm2)
687
688   | otherwise
689   = mkBalBranch mid_key1 mid_elt1 (deleteMax fm1) fm2
690   where
691     (mid_key1, mid_elt1) = findMax fm1
692     (mid_key2, mid_elt2) = findMin fm2
693
694 -- @glueVBal@ copes with arguments which can be of any size.
695 -- But: all keys in first arg are $<$ all keys in second.
696
697 glueVBal :: (Ord key OUTPUTABLE_key)
698          => FiniteMap key elt -> FiniteMap key elt
699          -> FiniteMap key elt
700
701 glueVBal EmptyFM fm2 = fm2
702 glueVBal fm1 EmptyFM = fm1
703 glueVBal fm_l@(Branch key_l elt_l _ fm_ll fm_lr)
704          fm_r@(Branch key_r elt_r _ fm_rl fm_rr)
705   | sIZE_RATIO * size_l < size_r
706   = mkBalBranch key_r elt_r (glueVBal fm_l fm_rl) fm_rr
707
708   | sIZE_RATIO * size_r < size_l
709   = mkBalBranch key_l elt_l fm_ll (glueVBal fm_lr fm_r)
710
711   | otherwise           -- We now need the same two cases as in glueBal above.
712   = glueBal fm_l fm_r
713   where
714     size_l = sizeFM fm_l
715     size_r = sizeFM fm_r
716
717
718 -- ---------------------------------------------------------------------------
719 -- Local utilities
720
721 splitLT, splitGT :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> key -> FiniteMap key elt
722
723 -- splitLT fm split_key  =  fm restricted to keys <  split_key
724 -- splitGT fm split_key  =  fm restricted to keys >  split_key
725
726 splitLT EmptyFM split_key = emptyFM
727 splitLT (Branch key elt _ fm_l fm_r) split_key
728 #if __GLASGOW_HASKELL__
729   = case _tagCmp split_key key of
730         _LT -> splitLT fm_l split_key
731         _GT -> mkVBalBranch key elt fm_l (splitLT fm_r split_key)
732         _EQ -> fm_l
733 #else
734   | split_key < key = splitLT fm_l split_key
735   | split_key > key = mkVBalBranch key elt fm_l (splitLT fm_r split_key)
736   | otherwise       = fm_l
737 #endif
738
739 splitGT EmptyFM split_key = emptyFM
740 splitGT (Branch key elt _ fm_l fm_r) split_key
741 #if __GLASGOW_HASKELL__
742   = case _tagCmp split_key key of
743         _GT -> splitGT fm_r split_key
744         _LT -> mkVBalBranch key elt (splitGT fm_l split_key) fm_r
745         _EQ -> fm_r
746 #else
747   | split_key > key = splitGT fm_r split_key
748   | split_key < key = mkVBalBranch key elt (splitGT fm_l split_key) fm_r
749   | otherwise       = fm_r
750 #endif
751
752 findMin :: FiniteMap key elt -> (key,elt)
753 findMin (Branch key elt _ EmptyFM _) = (key,elt)
754 findMin (Branch key elt _ fm_l    _) = findMin fm_l
755
756 deleteMin :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
757 deleteMin (Branch key elt _ EmptyFM fm_r) = fm_r
758 deleteMin (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt (deleteMin fm_l) fm_r
759
760 findMax :: FiniteMap key elt -> (key,elt)
761 findMax (Branch key elt _ _ EmptyFM) = (key,elt)
762 findMax (Branch key elt _ _    fm_r) = findMax fm_r
763
764 deleteMax :: (Ord key OUTPUTABLE_key) => FiniteMap key elt -> FiniteMap key elt
765 deleteMax (Branch key elt _ fm_l EmptyFM) = fm_l
766 deleteMax (Branch key elt _ fm_l    fm_r) = mkBalBranch key elt fm_l (deleteMax fm_r)
767
768
769 -- ---------------------------------------------------------------------------
770 -- Output-ery
771
772 #if defined(COMPILING_GHC) && defined(DEBUG_FINITEMAPS)
773
774 instance (Outputable key) => Outputable (FiniteMap key elt) where
775     ppr sty fm = pprX sty fm
776
777 pprX sty EmptyFM = ppChar '!'
778 pprX sty (Branch key elt sz fm_l fm_r)
779  = ppBesides [ppLparen, pprX sty fm_l, ppSP,
780               ppr sty key, ppSP, ppInt (IF_GHC(I# sz, sz)), ppSP,
781               pprX sty fm_r, ppRparen]
782 #endif
783
784 #ifndef COMPILING_GHC
785 instance (Eq key, Eq elt) => Eq (FiniteMap key elt) where
786   fm_1 == fm_2 = (sizeFM   fm_1 == sizeFM   fm_2) &&   -- quick test
787                  (fmToList fm_1 == fmToList fm_2)
788
789 {- NO: not clear what The Right Thing to do is:
790 instance (Ord key, Ord elt) => Ord (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 #endif
795
796 -- ---------------------------------------------------------------------------
797 -- Efficiency pragmas for GHC
798
799 -- When the FiniteMap module is used in GHC, we specialise it for
800 -- \tr{Uniques}, for dastardly efficiency reasons.
801
802 #if defined(COMPILING_GHC) && __GLASGOW_HASKELL__ && !defined(REALLY_HASKELL_1_3)
803
804 {-# SPECIALIZE addListToFM
805                 :: FiniteMap (FAST_STRING, FAST_STRING) elt -> [((FAST_STRING, FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
806                  , FiniteMap RdrName elt -> [(RdrName,elt)] -> FiniteMap RdrName elt
807     IF_NCG(COMMA   FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
808     #-}
809 {-# SPECIALIZE addListToFM_C
810                 :: (elt -> elt -> elt) -> FiniteMap TyCon elt -> [(TyCon,elt)] -> FiniteMap TyCon elt
811                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
812     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> [(Reg COMMA elt)] -> FiniteMap Reg elt)
813     #-}
814 {-# SPECIALIZE addToFM
815                 :: FiniteMap CLabel elt -> CLabel -> elt  -> FiniteMap CLabel elt
816                  , FiniteMap FAST_STRING elt -> FAST_STRING -> elt  -> FiniteMap FAST_STRING elt
817                  , FiniteMap (FAST_STRING, FAST_STRING) elt -> (FAST_STRING, FAST_STRING) -> elt  -> FiniteMap (FAST_STRING, FAST_STRING) elt
818                  , FiniteMap RdrName elt -> RdrName -> elt  -> FiniteMap RdrName elt
819                  , FiniteMap OrigName elt -> OrigName -> elt  -> FiniteMap OrigName elt
820     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> elt  -> FiniteMap Reg elt)
821     #-}
822 {-# SPECIALIZE addToFM_C
823                 :: (elt -> elt -> elt) -> FiniteMap (RdrName, RdrName) elt -> (RdrName, RdrName) -> elt -> FiniteMap (RdrName, RdrName) elt
824                  , (elt -> elt -> elt) -> FiniteMap (OrigName, OrigName) elt -> (OrigName, OrigName) -> elt -> FiniteMap (OrigName, OrigName) elt
825                  , (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FAST_STRING -> elt -> FiniteMap FAST_STRING elt
826     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> Reg -> elt -> FiniteMap Reg elt)
827     #-}
828 {-# SPECIALIZE bagToFM
829                 :: Bag (FAST_STRING,elt) -> FiniteMap FAST_STRING elt
830     #-}
831 {-# SPECIALIZE delListFromFM
832                 :: FiniteMap RdrName elt -> [RdrName]   -> FiniteMap RdrName elt
833                  , FiniteMap OrigName elt -> [OrigName]   -> FiniteMap OrigName elt
834                  , FiniteMap FAST_STRING elt -> [FAST_STRING]   -> FiniteMap FAST_STRING elt
835     IF_NCG(COMMA   FiniteMap Reg elt -> [Reg]   -> FiniteMap Reg elt)
836     #-}
837 {-# SPECIALIZE listToFM
838                 :: [([Char],elt)] -> FiniteMap [Char] elt
839                  , [(FAST_STRING,elt)] -> FiniteMap FAST_STRING elt
840                  , [((FAST_STRING,FAST_STRING),elt)] -> FiniteMap (FAST_STRING, FAST_STRING) elt
841                  , [(OrigName,elt)] -> FiniteMap OrigName elt
842     IF_NCG(COMMA   [(Reg COMMA elt)] -> FiniteMap Reg elt)
843     #-}
844 {-# SPECIALIZE lookupFM
845                 :: FiniteMap CLabel elt -> CLabel -> Maybe elt
846                  , FiniteMap [Char] elt -> [Char] -> Maybe elt
847                  , FiniteMap FAST_STRING elt -> FAST_STRING -> Maybe elt
848                  , FiniteMap (FAST_STRING,FAST_STRING) elt -> (FAST_STRING,FAST_STRING) -> Maybe elt
849                  , FiniteMap OrigName elt -> OrigName -> Maybe elt
850                  , FiniteMap (OrigName,OrigName) elt -> (OrigName,OrigName) -> Maybe elt
851                  , FiniteMap RdrName elt -> RdrName -> Maybe elt
852                  , FiniteMap (RdrName,RdrName) elt -> (RdrName,RdrName) -> Maybe elt
853     IF_NCG(COMMA   FiniteMap Reg elt -> Reg -> Maybe elt)
854     #-}
855 {-# SPECIALIZE lookupWithDefaultFM
856                 :: FiniteMap FAST_STRING elt -> elt -> FAST_STRING -> elt
857     IF_NCG(COMMA   FiniteMap Reg elt -> elt -> Reg -> elt)
858     #-}
859 {-# SPECIALIZE plusFM
860                 :: FiniteMap RdrName elt -> FiniteMap RdrName elt -> FiniteMap RdrName elt
861                  , FiniteMap OrigName elt -> FiniteMap OrigName elt -> FiniteMap OrigName elt
862                  , FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
863     IF_NCG(COMMA   FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
864     #-}
865 {-# SPECIALIZE plusFM_C
866                 :: (elt -> elt -> elt) -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt -> FiniteMap FAST_STRING elt
867     IF_NCG(COMMA   (elt -> elt -> elt) -> FiniteMap Reg elt -> FiniteMap Reg elt -> FiniteMap Reg elt)
868     #-}
869
870 #endif /* compiling for GHC */