2 # include "HsVersions.h"
6 -- At present the only one with a "nice" external interface
7 stronglyConnComp, stronglyConnCompR, SCC(..),
9 SYN_IE(Graph), SYN_IE(Vertex),
10 graphFromEdges, buildG, transposeG, reverseE, outdegree, indegree,
12 Tree(..), SYN_IE(Forest),
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 ------------------------------------------------------------------------------
34 #ifdef REALLY_HASKELL_1_3
36 #define ARR_ELT (COMMA)
48 #define MutableArray _MutableArray
52 import Maybes ( mapMaybe )
56 import Util ( Ord3(..),
62 %************************************************************************
66 %************************************************************************
69 data SCC vertex = AcyclicSCC vertex
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) [ ARR_ELT v (f v (t!v)) | v <- indices t ]
133 buildG :: Bounds -> [Edge] -> Graph
134 #ifdef REALLY_HASKELL_1_3
135 buildG bounds edges = accumArray (flip (:)) [] bounds edges
137 buildG bounds edges = accumArray (flip (:)) [] bounds [ARR_ELT k v | (k,v) <- edges]
140 transposeG :: Graph -> Graph
141 transposeG g = buildG (bounds g) (reverseE g)
143 reverseE :: Graph -> [Edge]
144 reverseE g = [ (w, v) | (v, w) <- edges g ]
146 outdegree :: Graph -> Table Int
147 outdegree = mapT numEdges
148 where numEdges v ws = length ws
150 indegree :: Graph -> Table Int
151 indegree = outdegree . transposeG
158 => [(node, key, [key])]
159 -> (Graph, Vertex -> (node, key, [key]))
161 = (graph, \v -> vertex_map ! v)
163 max_v = length edges - 1
164 bounds = (0,max_v) :: (Vertex, Vertex)
165 sorted_edges = sortLt lt edges
166 edges1 = zipWith ARR_ELT [0..] sorted_edges
168 graph = array bounds [ARR_ELT v (mapMaybe key_vertex ks) | ARR_ELT v (_, _, ks) <- edges1]
169 key_map = array bounds [ARR_ELT v k | ARR_ELT v (_, k, _ ) <- edges1]
170 vertex_map = array bounds edges1
172 (_,k1,_) `lt` (_,k2,_) = case k1 `cmp` k2 of { LT_ -> True; other -> False }
174 -- key_vertex :: key -> Maybe Vertex
175 -- returns Nothing for non-interesting vertices
176 key_vertex k = find 0 max_v
180 find a b = case cmp k (key_map ! mid) of
181 LT_ -> find a (mid-1)
183 GT_ -> find (mid+1) b
185 mid = (a + b) `div` 2
188 %************************************************************************
192 %************************************************************************
195 data Tree a = Node a (Forest a)
196 type Forest a = [Tree a]
198 mapTree :: (a -> b) -> (Tree a -> Tree b)
199 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
203 instance Show a => Show (Tree a) where
204 showsPrec p t s = showTree t ++ s
206 showTree :: Show a => Tree a -> String
207 showTree = drawTree . mapTree show
209 showForest :: Show a => Forest a -> String
210 showForest = unlines . map showTree
212 drawTree :: Tree String -> String
213 drawTree = unlines . draw
215 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
216 where this = s1 ++ x ++ " "
218 space n = take n (repeat ' ')
221 stLoop [t] = grp s2 " " (draw t)
222 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
224 rsLoop [t] = grp s5 " " (draw t)
225 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
227 grp fst rst = zipWith (++) (fst:repeat rst)
229 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
233 %************************************************************************
235 %* Depth first search
237 %************************************************************************
240 type Set s = MutableArray s Vertex Bool
242 mkEmpty :: Bounds -> ST s (Set s)
243 mkEmpty bnds = newArray bnds False
245 contains :: Set s -> Vertex -> ST s Bool
246 contains m v = readArray m v
248 include :: Set s -> Vertex -> ST s ()
249 include m v = writeArray m v True
253 dff :: Graph -> Forest Vertex
254 dff g = dfs g (vertices g)
256 dfs :: Graph -> [Vertex] -> Forest Vertex
257 dfs g vs = prune (bounds g) (map (generate g) vs)
259 generate :: Graph -> Vertex -> Tree Vertex
260 generate g v = Node v (map (generate g) (g!v))
262 prune :: Bounds -> Forest Vertex -> Forest Vertex
263 prune bnds ts = runST (mkEmpty bnds `thenST` \m ->
266 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
267 chop m [] = returnST []
268 chop m (Node v ts : us)
269 = contains m v `thenStrictlyST` \visited ->
273 include m v `thenStrictlyST` \_ ->
274 chop m ts `thenStrictlyST` \as ->
275 chop m us `thenStrictlyST` \bs ->
276 returnST (Node v as : bs)
280 %************************************************************************
284 %************************************************************************
286 ------------------------------------------------------------
287 -- Algorithm 1: depth first search numbering
288 ------------------------------------------------------------
291 --preorder :: Tree a -> [a]
292 preorder (Node a ts) = a : preorderF ts
294 preorderF :: Forest a -> [a]
295 preorderF ts = concat (map preorder ts)
297 preOrd :: Graph -> [Vertex]
298 preOrd = preorderF . dff
300 tabulate :: Bounds -> [Vertex] -> Table Int
301 tabulate bnds vs = array bnds (zipWith ARR_ELT vs [1..])
303 preArr :: Bounds -> Forest Vertex -> Table Int
304 preArr bnds = tabulate bnds . preorderF
308 ------------------------------------------------------------
309 -- Algorithm 2: topological sorting
310 ------------------------------------------------------------
313 --postorder :: Tree a -> [a]
314 postorder (Node a ts) = postorderF ts ++ [a]
316 postorderF :: Forest a -> [a]
317 postorderF ts = concat (map postorder ts)
319 postOrd :: Graph -> [Vertex]
320 postOrd = postorderF . dff
322 topSort :: Graph -> [Vertex]
323 topSort = reverse . postOrd
327 ------------------------------------------------------------
328 -- Algorithm 3: connected components
329 ------------------------------------------------------------
332 components :: Graph -> Forest Vertex
333 components = dff . undirected
335 undirected :: Graph -> Graph
336 undirected g = buildG (bounds g) (edges g ++ reverseE g)
340 -- Algorithm 4: strongly connected components
343 scc :: Graph -> Forest Vertex
344 scc g = dfs g (reverse (postOrd (transposeG g)))
348 ------------------------------------------------------------
349 -- Algorithm 5: Classifying edges
350 ------------------------------------------------------------
353 tree :: Bounds -> Forest Vertex -> Graph
354 tree bnds ts = buildG bnds (concat (map flat ts))
356 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
359 back :: Graph -> Table Int -> Graph
360 back g post = mapT select g
361 where select v ws = [ w | w <- ws, post!v < post!w ]
363 cross :: Graph -> Table Int -> Table Int -> Graph
364 cross g pre post = mapT select g
365 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
367 forward :: Graph -> Graph -> Table Int -> Graph
368 forward g tree pre = mapT select g
369 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
373 ------------------------------------------------------------
374 -- Algorithm 6: Finding reachable vertices
375 ------------------------------------------------------------
378 reachable :: Graph -> Vertex -> [Vertex]
379 reachable g v = preorderF (dfs g [v])
381 path :: Graph -> Vertex -> Vertex -> Bool
382 path g v w = w `elem` (reachable g v)
386 ------------------------------------------------------------
387 -- Algorithm 7: Biconnected components
388 ------------------------------------------------------------
391 bcc :: Graph -> Forest [Vertex]
392 bcc g = (concat . map bicomps . map (label g dnum)) forest
394 dnum = preArr (bounds g) forest
396 label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
397 label g dnum (Node v ts) = Node (v,dnum!v,lv) us
398 where us = map (label g dnum) ts
399 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
400 ++ [lu | Node (u,du,lu) xs <- us])
402 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
403 bicomps (Node (v,dv,lv) ts)
404 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
406 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
407 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
408 where collected = map collect ts
409 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
410 cs = concat [ if lw<dv then us else [Node (v:ws) us]
411 | (lw, Node ws us) <- collected ]