2 #if defined(COMPILING_GHC)
3 # include "HsVersions.h"
8 -- At present the only one with a "nice" external interface
9 stronglyConnComp, stronglyConnCompR, SCC(..),
11 SYN_IE(Graph), SYN_IE(Vertex),
12 graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
14 Tree(..), SYN_IE(Forest),
27 ------------------------------------------------------------------------------
28 -- A version of the graph algorithms described in:
30 -- ``Lazy Depth-First Search and Linear Graph Algorithms in Haskell''
31 -- by David King and John Launchbury
33 -- Also included is some additional code for printing tree structures ...
34 ------------------------------------------------------------------------------
36 #ifdef REALLY_HASKELL_1_3
38 #define ARR_ELT (COMMA)
50 #define MutableArray _MutableArray
54 import Maybes ( mapMaybe )
58 import Util ( Ord3(..),
64 %************************************************************************
68 %************************************************************************
71 data SCC vertex = AcyclicSCC vertex
76 => [(node, key, [key])] -- The graph; its ok for the
77 -- out-list to contain keys which arent
78 -- a vertex key, they are ignored
81 stronglyConnComp edges
82 = map get_node (stronglyConnCompR edges)
84 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
85 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
87 -- The "R" interface is used when you expect to apply SCC to
88 -- the (some of) the result of SCC, so you dont want to lose the dependency info
91 => [(node, key, [key])] -- The graph; its ok for the
92 -- out-list to contain keys which arent
93 -- a vertex key, they are ignored
94 -> [SCC (node, key, [key])]
96 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
97 stronglyConnCompR edges
100 (graph, vertex_fn) = graphFromEdges edges
102 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
103 | otherwise = AcyclicSCC (vertex_fn v)
104 decode other = CyclicSCC (dec other [])
106 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
107 mentions_itself v = v `elem` (graph ! v)
110 %************************************************************************
114 %************************************************************************
119 type Table a = Array Vertex a
120 type Graph = Table [Vertex]
121 type Bounds = (Vertex, Vertex)
122 type Edge = (Vertex, Vertex)
126 vertices :: Graph -> [Vertex]
129 edges :: Graph -> [Edge]
130 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
132 mapT :: (Vertex -> a -> b) -> Table a -> Table b
133 mapT f t = array (bounds t) [ ARR_ELT v (f v (t!v)) | v <- indices t ]
135 buildG :: Bounds -> [Edge] -> Graph
136 #ifdef REALLY_HASKELL_1_3
137 buildG bounds edges = accumArray (flip (:)) [] bounds edges
139 buildG bounds edges = accumArray (flip (:)) [] bounds [ARR_ELT k v | (k,v) <- 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 ARR_ELT [0..] sorted_edges
170 graph = array bounds [ARR_ELT v (mapMaybe key_vertex ks) | ARR_ELT v (_, _, ks) <- edges1]
171 key_map = array bounds [ARR_ELT v k | ARR_ELT v (_, k, _ ) <- edges1]
172 vertex_map = array bounds edges1
174 (_,k1,_) `lt` (_,k2,_) = case k1 `cmp` 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 cmp k (key_map ! mid) of
183 LT_ -> find a (mid-1)
185 GT_ -> find (mid+1) b
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 = take n (repeat ' ')
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 type Set s = MutableArray s Vertex Bool
244 mkEmpty :: Bounds -> ST s (Set s)
245 mkEmpty bnds = newArray bnds False
247 contains :: Set s -> Vertex -> ST s Bool
248 contains m v = readArray m v
250 include :: Set s -> Vertex -> ST s ()
251 include m v = writeArray m v True
255 dff :: Graph -> Forest Vertex
256 dff g = dfs g (vertices g)
258 dfs :: Graph -> [Vertex] -> Forest Vertex
259 dfs g vs = prune (bounds g) (map (generate g) vs)
261 generate :: Graph -> Vertex -> Tree Vertex
262 generate g v = Node v (map (generate g) (g!v))
264 prune :: Bounds -> Forest Vertex -> Forest Vertex
265 prune bnds ts = runST (mkEmpty bnds `thenST` \m ->
268 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
269 chop m [] = returnST []
270 chop m (Node v ts : us)
271 = contains m v `thenStrictlyST` \visited ->
275 include m v `thenStrictlyST` \_ ->
276 chop m ts `thenStrictlyST` \as ->
277 chop m us `thenStrictlyST` \bs ->
278 returnST (Node v as : bs)
282 %************************************************************************
286 %************************************************************************
288 ------------------------------------------------------------
289 -- Algorithm 1: depth first search numbering
290 ------------------------------------------------------------
293 --preorder :: Tree a -> [a]
294 preorder (Node a ts) = a : preorderF ts
296 preorderF :: Forest a -> [a]
297 preorderF ts = concat (map preorder ts)
299 preOrd :: Graph -> [Vertex]
300 preOrd = preorderF . dff
302 tabulate :: Bounds -> [Vertex] -> Table Int
303 tabulate bnds vs = array bnds (zipWith ARR_ELT vs [1..])
305 preArr :: Bounds -> Forest Vertex -> Table Int
306 preArr bnds = tabulate bnds . preorderF
310 ------------------------------------------------------------
311 -- Algorithm 2: topological sorting
312 ------------------------------------------------------------
315 --postorder :: Tree a -> [a]
316 postorder (Node a ts) = postorderF ts ++ [a]
318 postorderF :: Forest a -> [a]
319 postorderF ts = concat (map postorder ts)
321 postOrd :: Graph -> [Vertex]
322 postOrd = postorderF . dff
324 topSort :: Graph -> [Vertex]
325 topSort = reverse . postOrd
329 ------------------------------------------------------------
330 -- Algorithm 3: connected components
331 ------------------------------------------------------------
334 components :: Graph -> Forest Vertex
335 components = dff . undirected
337 undirected :: Graph -> Graph
338 undirected g = buildG (bounds g) (edges g ++ reverseE g)
342 -- Algorithm 4: strongly connected components
345 scc :: Graph -> Forest Vertex
346 scc g = dfs g (reverse (postOrd (transposeG g)))
350 ------------------------------------------------------------
351 -- Algorithm 5: Classifying edges
352 ------------------------------------------------------------
355 tree :: Bounds -> Forest Vertex -> Graph
356 tree bnds ts = buildG bnds (concat (map flat ts))
358 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
361 back :: Graph -> Table Int -> Graph
362 back g post = mapT select g
363 where select v ws = [ w | w <- ws, post!v < post!w ]
365 cross :: Graph -> Table Int -> Table Int -> Graph
366 cross g pre post = mapT select g
367 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
369 forward :: Graph -> Graph -> Table Int -> Graph
370 forward g tree pre = mapT select g
371 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
375 ------------------------------------------------------------
376 -- Algorithm 6: Finding reachable vertices
377 ------------------------------------------------------------
380 reachable :: Graph -> Vertex -> [Vertex]
381 reachable g v = preorderF (dfs g [v])
383 path :: Graph -> Vertex -> Vertex -> Bool
384 path g v w = w `elem` (reachable g v)
388 ------------------------------------------------------------
389 -- Algorithm 7: Biconnected components
390 ------------------------------------------------------------
393 bcc :: Graph -> Forest [Vertex]
394 bcc g = (concat . map bicomps . map (label g dnum)) forest
396 dnum = preArr (bounds g) forest
398 label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
399 label g dnum (Node v ts) = Node (v,dnum!v,lv) us
400 where us = map (label g dnum) ts
401 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
402 ++ [lu | Node (u,du,lu) xs <- us])
404 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
405 bicomps (Node (v,dv,lv) ts)
406 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
408 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
409 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
410 where collected = map collect ts
411 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
412 cs = concat [ if lw<dv then us else [Node (v:ws) us]
413 | (lw, Node ws us) <- collected ]