4 -- At present the only one with a "nice" external interface
5 stronglyConnComp, stronglyConnCompR, SCC(..), flattenSCC, flattenSCCs,
8 graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
23 # include "HsVersions.h"
25 ------------------------------------------------------------------------------
26 -- A version of the graph algorithms described in:
28 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
29 -- by David King and John Launchbury
31 -- Also included is some additional code for printing tree structures ...
32 ------------------------------------------------------------------------------
35 #define ARR_ELT (COMMA)
37 import Util ( sortLt )
50 %************************************************************************
54 %************************************************************************
57 data SCC vertex = AcyclicSCC vertex
60 flattenSCCs :: [SCC a] -> [a]
61 flattenSCCs = concatMap flattenSCC
63 flattenSCC (AcyclicSCC v) = [v]
64 flattenSCC (CyclicSCC vs) = vs
66 instance Outputable a => Outputable (SCC a) where
67 ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
68 ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
74 => [(node, key, [key])] -- The graph; its ok for the
75 -- out-list to contain keys which arent
76 -- a vertex key, they are ignored
79 stronglyConnComp edges
80 = map get_node (stronglyConnCompR edges)
82 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
83 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
85 -- The "R" interface is used when you expect to apply SCC to
86 -- the (some of) the result of SCC, so you dont want to lose the dependency info
89 => [(node, key, [key])] -- The graph; its ok for the
90 -- out-list to contain keys which arent
91 -- a vertex key, they are ignored
92 -> [SCC (node, key, [key])]
94 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
95 stronglyConnCompR edges
98 (graph, vertex_fn) = graphFromEdges edges
100 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
101 | otherwise = AcyclicSCC (vertex_fn v)
102 decode other = CyclicSCC (dec other [])
104 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
105 mentions_itself v = v `elem` (graph ! v)
108 %************************************************************************
112 %************************************************************************
117 type Table a = Array Vertex a
118 type Graph = Table [Vertex]
119 type Bounds = (Vertex, Vertex)
120 type Edge = (Vertex, Vertex)
124 vertices :: Graph -> [Vertex]
127 edges :: Graph -> [Edge]
128 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
130 mapT :: (Vertex -> a -> b) -> Table a -> Table b
131 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
133 buildG :: Bounds -> [Edge] -> Graph
134 buildG bounds edges = accumArray (flip (:)) [] bounds edges
136 transposeG :: Graph -> Graph
137 transposeG g = buildG (bounds g) (reverseE g)
139 reverseE :: Graph -> [Edge]
140 reverseE g = [ (w, v) | (v, w) <- edges g ]
142 outdegree :: Graph -> Table Int
143 outdegree = mapT numEdges
144 where numEdges v ws = length ws
146 indegree :: Graph -> Table Int
147 indegree = outdegree . transposeG
154 => [(node, key, [key])]
155 -> (Graph, Vertex -> (node, key, [key]))
157 = (graph, \v -> vertex_map ! v)
159 max_v = length edges - 1
160 bounds = (0,max_v) :: (Vertex, Vertex)
161 sorted_edges = sortLt lt edges
162 edges1 = zipWith (,) [0..] sorted_edges
164 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
165 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
166 vertex_map = array bounds edges1
168 (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
170 -- key_vertex :: key -> Maybe Vertex
171 -- returns Nothing for non-interesting vertices
172 key_vertex k = find 0 max_v
176 find a b = case compare k (key_map ! mid) of
181 mid = (a + b) `div` 2
184 %************************************************************************
188 %************************************************************************
191 data Tree a = Node a (Forest a)
192 type Forest a = [Tree a]
194 mapTree :: (a -> b) -> (Tree a -> Tree b)
195 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
199 instance Show a => Show (Tree a) where
200 showsPrec p t s = showTree t ++ s
202 showTree :: Show a => Tree a -> String
203 showTree = drawTree . mapTree show
205 showForest :: Show a => Forest a -> String
206 showForest = unlines . map showTree
208 drawTree :: Tree String -> String
209 drawTree = unlines . draw
211 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
212 where this = s1 ++ x ++ " "
214 space n = take n (repeat ' ')
217 stLoop [t] = grp s2 " " (draw t)
218 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
220 rsLoop [t] = grp s5 " " (draw t)
221 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
223 grp fst rst = zipWith (++) (fst:repeat rst)
225 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
229 %************************************************************************
231 %* Depth first search
233 %************************************************************************
236 type Set s = STArray s Vertex Bool
238 mkEmpty :: Bounds -> ST s (Set s)
239 mkEmpty bnds = newSTArray bnds False
241 contains :: Set s -> Vertex -> ST s Bool
242 contains m v = readSTArray m v
244 include :: Set s -> Vertex -> ST s ()
245 include m v = writeSTArray m v True
249 dff :: Graph -> Forest Vertex
250 dff g = dfs g (vertices g)
252 dfs :: Graph -> [Vertex] -> Forest Vertex
253 dfs g vs = prune (bounds g) (map (generate g) vs)
255 generate :: Graph -> Vertex -> Tree Vertex
256 generate g v = Node v (map (generate g) (g!v))
258 prune :: Bounds -> Forest Vertex -> Forest Vertex
259 prune bnds ts = runST (mkEmpty bnds >>= \m ->
262 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
263 chop m [] = return []
264 chop m (Node v ts : us)
265 = contains m v >>= \visited ->
269 include m v >>= \_ ->
272 return (Node v as : bs)
276 %************************************************************************
280 %************************************************************************
282 ------------------------------------------------------------
283 -- Algorithm 1: depth first search numbering
284 ------------------------------------------------------------
287 --preorder :: Tree a -> [a]
288 preorder (Node a ts) = a : preorderF ts
290 preorderF :: Forest a -> [a]
291 preorderF ts = concat (map preorder ts)
293 preOrd :: Graph -> [Vertex]
294 preOrd = preorderF . dff
296 tabulate :: Bounds -> [Vertex] -> Table Int
297 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
299 preArr :: Bounds -> Forest Vertex -> Table Int
300 preArr bnds = tabulate bnds . preorderF
304 ------------------------------------------------------------
305 -- Algorithm 2: topological sorting
306 ------------------------------------------------------------
309 --postorder :: Tree a -> [a]
310 postorder (Node a ts) = postorderF ts ++ [a]
312 postorderF :: Forest a -> [a]
313 postorderF ts = concat (map postorder ts)
315 postOrd :: Graph -> [Vertex]
316 postOrd = postorderF . dff
318 topSort :: Graph -> [Vertex]
319 topSort = reverse . postOrd
323 ------------------------------------------------------------
324 -- Algorithm 3: connected components
325 ------------------------------------------------------------
328 components :: Graph -> Forest Vertex
329 components = dff . undirected
331 undirected :: Graph -> Graph
332 undirected g = buildG (bounds g) (edges g ++ reverseE g)
336 -- Algorithm 4: strongly connected components
339 scc :: Graph -> Forest Vertex
340 scc g = dfs g (reverse (postOrd (transposeG g)))
344 ------------------------------------------------------------
345 -- Algorithm 5: Classifying edges
346 ------------------------------------------------------------
349 tree :: Bounds -> Forest Vertex -> Graph
350 tree bnds ts = buildG bnds (concat (map flat ts))
352 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
355 back :: Graph -> Table Int -> Graph
356 back g post = mapT select g
357 where select v ws = [ w | w <- ws, post!v < post!w ]
359 cross :: Graph -> Table Int -> Table Int -> Graph
360 cross g pre post = mapT select g
361 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
363 forward :: Graph -> Graph -> Table Int -> Graph
364 forward g tree pre = mapT select g
365 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
369 ------------------------------------------------------------
370 -- Algorithm 6: Finding reachable vertices
371 ------------------------------------------------------------
374 reachable :: Graph -> Vertex -> [Vertex]
375 reachable g v = preorderF (dfs g [v])
377 path :: Graph -> Vertex -> Vertex -> Bool
378 path g v w = w `elem` (reachable g v)
382 ------------------------------------------------------------
383 -- Algorithm 7: Biconnected components
384 ------------------------------------------------------------
387 bcc :: Graph -> Forest [Vertex]
388 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
390 dnum = preArr (bounds g) forest
392 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
393 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
394 where us = map (do_label g dnum) ts
395 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
396 ++ [lu | Node (u,du,lu) xs <- us])
398 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
399 bicomps (Node (v,dv,lv) ts)
400 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
402 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
403 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
404 where collected = map collect ts
405 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
406 cs = concat [ if lw<dv then us else [Node (v:ws) us]
407 | (lw, Node ws us) <- collected ]