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 )
48 #if __GLASGOW_HASKELL__ >= 504
49 import Data.Array.ST hiding ( indices, bounds )
56 %************************************************************************
60 %************************************************************************
63 data SCC vertex = AcyclicSCC vertex
66 flattenSCCs :: [SCC a] -> [a]
67 flattenSCCs = concatMap flattenSCC
69 flattenSCC (AcyclicSCC v) = [v]
70 flattenSCC (CyclicSCC vs) = vs
72 instance Outputable a => Outputable (SCC a) where
73 ppr (AcyclicSCC v) = text "NONREC" $$ (nest 3 (ppr v))
74 ppr (CyclicSCC vs) = text "REC" $$ (nest 3 (vcat (map ppr vs)))
80 => [(node, key, [key])] -- The graph; its ok for the
81 -- out-list to contain keys which arent
82 -- a vertex key, they are ignored
85 stronglyConnComp edges
86 = map get_node (stronglyConnCompR edges)
88 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
89 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
91 -- The "R" interface is used when you expect to apply SCC to
92 -- the (some of) the result of SCC, so you dont want to lose the dependency info
95 => [(node, key, [key])] -- The graph; its ok for the
96 -- out-list to contain keys which arent
97 -- a vertex key, they are ignored
98 -> [SCC (node, key, [key])] -- Topologically sorted
100 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
101 stronglyConnCompR edges
104 (graph, vertex_fn) = graphFromEdges edges
106 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
107 | otherwise = AcyclicSCC (vertex_fn v)
108 decode other = CyclicSCC (dec other [])
110 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
111 mentions_itself v = v `elem` (graph ! v)
114 %************************************************************************
118 %************************************************************************
123 type Table a = Array Vertex a
124 type Graph = Table [Vertex]
125 type Bounds = (Vertex, Vertex)
126 type Edge = (Vertex, Vertex)
130 vertices :: Graph -> [Vertex]
133 edges :: Graph -> [Edge]
134 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
136 mapT :: (Vertex -> a -> b) -> Table a -> Table b
137 mapT f t = array (bounds t) [ (,) v (f v (t!v)) | v <- indices t ]
139 buildG :: Bounds -> [Edge] -> Graph
140 buildG bounds edges = accumArray (flip (:)) [] bounds edges
142 transposeG :: Graph -> Graph
143 transposeG g = buildG (bounds g) (reverseE g)
145 reverseE :: Graph -> [Edge]
146 reverseE g = [ (w, v) | (v, w) <- edges g ]
148 outdegree :: Graph -> Table Int
149 outdegree = mapT numEdges
150 where numEdges v ws = length ws
152 indegree :: Graph -> Table Int
153 indegree = outdegree . transposeG
160 => [(node, key, [key])]
161 -> (Graph, Vertex -> (node, key, [key]))
163 = (graph, \v -> vertex_map ! v)
165 max_v = length edges - 1
166 bounds = (0,max_v) :: (Vertex, Vertex)
167 sorted_edges = sortLt lt edges
168 edges1 = zipWith (,) [0..] sorted_edges
170 graph = array bounds [(,) v (mapMaybe key_vertex ks) | (,) v (_, _, ks) <- edges1]
171 key_map = array bounds [(,) v k | (,) v (_, k, _ ) <- edges1]
172 vertex_map = array bounds edges1
174 (_,k1,_) `lt` (_,k2,_) = case k1 `compare` k2 of { LT -> True; other -> False }
176 -- key_vertex :: key -> Maybe Vertex
177 -- returns Nothing for non-interesting vertices
178 key_vertex k = find 0 max_v
182 find a b = case compare k (key_map ! mid) of
187 mid = (a + b) `div` 2
190 %************************************************************************
194 %************************************************************************
197 data Tree a = Node a (Forest a)
198 type Forest a = [Tree a]
200 mapTree :: (a -> b) -> (Tree a -> Tree b)
201 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
205 instance Show a => Show (Tree a) where
206 showsPrec p t s = showTree t ++ s
208 showTree :: Show a => Tree a -> String
209 showTree = drawTree . mapTree show
211 showForest :: Show a => Forest a -> String
212 showForest = unlines . map showTree
214 drawTree :: Tree String -> String
215 drawTree = unlines . draw
217 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
218 where this = s1 ++ x ++ " "
220 space n = replicate n ' '
223 stLoop [t] = grp s2 " " (draw t)
224 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
226 rsLoop [t] = grp s5 " " (draw t)
227 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
229 grp fst rst = zipWith (++) (fst:repeat rst)
231 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
235 %************************************************************************
237 %* Depth first search
239 %************************************************************************
242 #if __GLASGOW_HASKELL__ >= 504
243 newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e)
244 newSTArray = newArray
246 readSTArray :: Ix i => STArray s i e -> i -> ST s e
247 readSTArray = readArray
249 writeSTArray :: Ix i => STArray s i e -> i -> e -> ST s ()
250 writeSTArray = writeArray
253 type Set s = STArray s Vertex Bool
255 mkEmpty :: Bounds -> ST s (Set s)
256 mkEmpty bnds = newSTArray bnds False
258 contains :: Set s -> Vertex -> ST s Bool
259 contains m v = readSTArray m v
261 include :: Set s -> Vertex -> ST s ()
262 include m v = writeSTArray m v True
266 dff :: Graph -> Forest Vertex
267 dff g = dfs g (vertices g)
269 dfs :: Graph -> [Vertex] -> Forest Vertex
270 dfs g vs = prune (bounds g) (map (generate g) vs)
272 generate :: Graph -> Vertex -> Tree Vertex
273 generate g v = Node v (map (generate g) (g!v))
275 prune :: Bounds -> Forest Vertex -> Forest Vertex
276 prune bnds ts = runST (mkEmpty bnds >>= \m ->
279 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
280 chop m [] = return []
281 chop m (Node v ts : us)
282 = contains m v >>= \visited ->
286 include m v >>= \_ ->
289 return (Node v as : bs)
293 %************************************************************************
297 %************************************************************************
299 ------------------------------------------------------------
300 -- Algorithm 1: depth first search numbering
301 ------------------------------------------------------------
304 --preorder :: Tree a -> [a]
305 preorder (Node a ts) = a : preorderF ts
307 preorderF :: Forest a -> [a]
308 preorderF ts = concat (map preorder ts)
310 preOrd :: Graph -> [Vertex]
311 preOrd = preorderF . dff
313 tabulate :: Bounds -> [Vertex] -> Table Int
314 tabulate bnds vs = array bnds (zipWith (,) vs [1..])
316 preArr :: Bounds -> Forest Vertex -> Table Int
317 preArr bnds = tabulate bnds . preorderF
321 ------------------------------------------------------------
322 -- Algorithm 2: topological sorting
323 ------------------------------------------------------------
326 --postorder :: Tree a -> [a]
327 postorder (Node a ts) = postorderF ts ++ [a]
329 postorderF :: Forest a -> [a]
330 postorderF ts = concat (map postorder ts)
332 postOrd :: Graph -> [Vertex]
333 postOrd = postorderF . dff
335 topSort :: Graph -> [Vertex]
336 topSort = reverse . postOrd
340 ------------------------------------------------------------
341 -- Algorithm 3: connected components
342 ------------------------------------------------------------
345 components :: Graph -> Forest Vertex
346 components = dff . undirected
348 undirected :: Graph -> Graph
349 undirected g = buildG (bounds g) (edges g ++ reverseE g)
353 -- Algorithm 4: strongly connected components
356 scc :: Graph -> Forest Vertex
357 scc g = dfs g (reverse (postOrd (transposeG g)))
361 ------------------------------------------------------------
362 -- Algorithm 5: Classifying edges
363 ------------------------------------------------------------
366 tree :: Bounds -> Forest Vertex -> Graph
367 tree bnds ts = buildG bnds (concat (map flat ts))
369 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
372 back :: Graph -> Table Int -> Graph
373 back g post = mapT select g
374 where select v ws = [ w | w <- ws, post!v < post!w ]
376 cross :: Graph -> Table Int -> Table Int -> Graph
377 cross g pre post = mapT select g
378 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
380 forward :: Graph -> Graph -> Table Int -> Graph
381 forward g tree pre = mapT select g
382 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
386 ------------------------------------------------------------
387 -- Algorithm 6: Finding reachable vertices
388 ------------------------------------------------------------
391 reachable :: Graph -> Vertex -> [Vertex]
392 reachable g v = preorderF (dfs g [v])
394 path :: Graph -> Vertex -> Vertex -> Bool
395 path g v w = w `elem` (reachable g v)
399 ------------------------------------------------------------
400 -- Algorithm 7: Biconnected components
401 ------------------------------------------------------------
404 bcc :: Graph -> Forest [Vertex]
405 bcc g = (concat . map bicomps . map (do_label g dnum)) forest
407 dnum = preArr (bounds g) forest
409 do_label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
410 do_label g dnum (Node v ts) = Node (v,dnum!v,lv) us
411 where us = map (do_label g dnum) ts
412 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
413 ++ [lu | Node (u,du,lu) xs <- us])
415 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
416 bicomps (Node (v,dv,lv) ts)
417 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
419 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
420 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
421 where collected = map collect ts
422 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
423 cs = concat [ if lw<dv then us else [Node (v:ws) us]
424 | (lw, Node ws us) <- collected ]