Make the dynamic linker thread-safe.
[ghc-hetmet.git] / compiler / utils / ListSetOps.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5 \section[ListSetOps]{Set-like operations on lists}
6
7 \begin{code}
8 module ListSetOps (
9         unionLists, minusList, insertList,
10
11         -- Association lists
12         Assoc, assoc, assocMaybe, assocUsing, assocDefault, assocDefaultUsing,
13         emptyAssoc, unitAssoc, mapAssoc, plusAssoc_C, extendAssoc_C,
14         mkLookupFun, findInList, assocElts,
15
16         -- Duplicate handling
17         hasNoDups, runs, removeDups, findDupsEq,
18         equivClasses, equivClassesByUniq
19
20    ) where
21
22 import Outputable
23 import Unique
24 import UniqFM
25 import Util
26
27 import Data.List
28 \end{code}
29
30
31 %************************************************************************
32 %*                                                                      *
33         Treating lists as sets
34         Assumes the lists contain no duplicates, but are unordered
35 %*                                                                      *
36 %************************************************************************
37
38 \begin{code}
39 insertList :: Eq a => a -> [a] -> [a]
40 -- Assumes the arg list contains no dups; guarantees the result has no dups
41 insertList x xs | isIn "insert" x xs = xs
42                 | otherwise          = x : xs
43
44 unionLists :: (Eq a) => [a] -> [a] -> [a]
45 -- Assumes that the arguments contain no duplicates
46 unionLists xs ys = [x | x <- xs, isn'tIn "unionLists" x ys] ++ ys
47
48 minusList :: (Eq a) => [a] -> [a] -> [a]
49 -- Everything in the first list that is not in the second list:
50 minusList xs ys = [ x | x <- xs, isn'tIn "minusList" x ys]
51 \end{code}
52
53
54 %************************************************************************
55 %*                                                                      *
56 \subsection[Utils-assoc]{Association lists}
57 %*                                                                      *
58 %************************************************************************
59
60 Inefficient finite maps based on association lists and equality.
61
62 \begin{code}
63 -- A finite mapping based on equality and association lists
64 type Assoc a b = [(a,b)]
65
66 emptyAssoc        :: Assoc a b
67 unitAssoc         :: a -> b -> Assoc a b
68 assocElts         :: Assoc a b -> [(a,b)]
69 assoc             :: (Eq a) => String -> Assoc a b -> a -> b
70 assocDefault      :: (Eq a) => b -> Assoc a b -> a -> b
71 assocUsing        :: (a -> a -> Bool) -> String -> Assoc a b -> a -> b
72 assocMaybe        :: (Eq a) => Assoc a b -> a -> Maybe b
73 assocDefaultUsing :: (a -> a -> Bool) -> b -> Assoc a b -> a -> b
74 mapAssoc          :: (b -> c) -> Assoc a b -> Assoc a c
75 extendAssoc_C     :: (Eq a) => (b -> b -> b) -> Assoc a b -> (a,b)     -> Assoc a b
76 plusAssoc_C       :: (Eq a) => (b -> b -> b) -> Assoc a b -> Assoc a b -> Assoc a b
77         -- combining fn takes (old->new->result)
78
79 emptyAssoc    = []
80 unitAssoc a b = [(a,b)]
81 assocElts xs  = xs
82
83 assocDefaultUsing _  deflt []             _   = deflt
84 assocDefaultUsing eq deflt ((k,v) : rest) key
85   | k `eq` key = v
86   | otherwise  = assocDefaultUsing eq deflt rest key
87
88 assoc crash_msg         list key = assocDefaultUsing (==) (panic ("Failed in assoc: " ++ crash_msg)) list key
89 assocDefault deflt      list key = assocDefaultUsing (==) deflt list key
90 assocUsing eq crash_msg list key = assocDefaultUsing eq (panic ("Failed in assoc: " ++ crash_msg)) list key
91
92 assocMaybe alist key
93   = lookup alist
94   where
95     lookup []             = Nothing
96     lookup ((tv,ty):rest) = if key == tv then Just ty else lookup rest
97
98 mapAssoc f alist = [(key, f val) | (key,val) <- alist]
99
100 plusAssoc_C _       []  new = new -- Shortcut for common case
101 plusAssoc_C combine old new = foldl (extendAssoc_C combine) old new
102
103 extendAssoc_C combine old_list (new_key, new_val)
104   = go old_list
105   where
106     go [] = [(new_key, new_val)]
107     go ((old_key, old_val) : old_list)
108      | new_key == old_key = ((old_key, old_val `combine` new_val) : old_list)
109      | otherwise          = (old_key, old_val) : go old_list
110 \end{code}
111
112
113 @mkLookupFun eq alist@ is a function which looks up
114 its argument in the association list @alist@, returning a Maybe type.
115 @mkLookupFunDef@ is similar except that it is given a value to return
116 on failure.
117
118 \begin{code}
119 mkLookupFun :: (key -> key -> Bool)     -- Equality predicate
120             -> [(key,val)]              -- The assoc list
121             -> key                      -- The key
122             -> Maybe val                -- The corresponding value
123
124 mkLookupFun eq alist s
125   = case [a | (s',a) <- alist, s' `eq` s] of
126       []    -> Nothing
127       (a:_) -> Just a
128
129 findInList :: (a -> Bool) -> [a] -> Maybe a
130 findInList _ [] = Nothing
131 findInList p (x:xs) | p x       = Just x
132                     | otherwise = findInList p xs
133 \end{code}
134
135
136 %************************************************************************
137 %*                                                                      *
138 \subsection[Utils-dups]{Duplicate-handling}
139 %*                                                                      *
140 %************************************************************************
141
142 \begin{code}
143 hasNoDups :: (Eq a) => [a] -> Bool
144
145 hasNoDups xs = f [] xs
146   where
147     f _           []     = True
148     f seen_so_far (x:xs) = if x `is_elem` seen_so_far
149                            then False
150                            else f (x:seen_so_far) xs
151
152     is_elem = isIn "hasNoDups"
153 \end{code}
154
155 \begin{code}
156 equivClasses :: (a -> a -> Ordering) -- Comparison
157              -> [a]
158              -> [[a]]
159
160 equivClasses _         []  = []
161 equivClasses _   stuff@[_] = [stuff]
162 equivClasses cmp items     = runs eq (sortLe le items)
163   where
164     eq a b = case cmp a b of { EQ -> True; _ -> False }
165     le a b = case cmp a b of { LT -> True; EQ -> True; GT -> False }
166 \end{code}
167
168 The first cases in @equivClasses@ above are just to cut to the point
169 more quickly...
170
171 @runs@ groups a list into a list of lists, each sublist being a run of
172 identical elements of the input list. It is passed a predicate @p@ which
173 tells when two elements are equal.
174
175 \begin{code}
176 runs :: (a -> a -> Bool) -- Equality
177      -> [a]
178      -> [[a]]
179
180 runs _ []     = []
181 runs p (x:xs) = case (span (p x) xs) of
182                 (first, rest) -> (x:first) : (runs p rest)
183 \end{code}
184
185 \begin{code}
186 removeDups :: (a -> a -> Ordering) -- Comparison function
187            -> [a]
188            -> ([a],     -- List with no duplicates
189                [[a]])   -- List of duplicate groups.  One representative from
190                         -- each group appears in the first result
191
192 removeDups _   []  = ([], [])
193 removeDups _   [x] = ([x],[])
194 removeDups cmp xs
195   = case (mapAccumR collect_dups [] (equivClasses cmp xs)) of { (dups, xs') ->
196     (xs', dups) }
197   where
198     collect_dups _           []         = panic "ListSetOps: removeDups"
199     collect_dups dups_so_far [x]        = (dups_so_far,      x)
200     collect_dups dups_so_far dups@(x:_) = (dups:dups_so_far, x)
201
202 findDupsEq :: (a->a->Bool) -> [a] -> [[a]]
203 findDupsEq _  [] = []
204 findDupsEq eq (x:xs) | null eq_xs  = findDupsEq eq xs
205                      | otherwise   = (x:eq_xs) : findDupsEq eq neq_xs
206     where (eq_xs, neq_xs) = partition (eq x) xs
207 \end{code}
208
209
210 \begin{code}
211 equivClassesByUniq :: (a -> Unique) -> [a] -> [[a]]
212         -- NB: it's *very* important that if we have the input list [a,b,c],
213         -- where a,b,c all have the same unique, then we get back the list
214         --      [a,b,c]
215         -- not
216         --      [c,b,a]
217         -- Hence the use of foldr, plus the reversed-args tack_on below
218 equivClassesByUniq get_uniq xs
219   = eltsUFM (foldr add emptyUFM xs)
220   where
221     add a ufm = addToUFM_C tack_on ufm (get_uniq a) [a]
222     tack_on old new = new++old
223 \end{code}
224