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)
44 # if __GLASGOW_HASKELL__ >= 209
45 import GlaExts ( thenST, returnST )
52 #define MutableArray _MutableArray
56 import Maybes ( mapMaybe )
60 import Util ( Ord3(..),
66 %************************************************************************
70 %************************************************************************
73 data SCC vertex = AcyclicSCC vertex
78 => [(node, key, [key])] -- The graph; its ok for the
79 -- out-list to contain keys which arent
80 -- a vertex key, they are ignored
83 stronglyConnComp edges
84 = map get_node (stronglyConnCompR edges)
86 get_node (AcyclicSCC (n, _, _)) = AcyclicSCC n
87 get_node (CyclicSCC triples) = CyclicSCC [n | (n,_,_) <- triples]
89 -- The "R" interface is used when you expect to apply SCC to
90 -- the (some of) the result of SCC, so you dont want to lose the dependency info
93 => [(node, key, [key])] -- The graph; its ok for the
94 -- out-list to contain keys which arent
95 -- a vertex key, they are ignored
96 -> [SCC (node, key, [key])]
98 stronglyConnCompR [] = [] -- added to avoid creating empty array in graphFromEdges -- SOF
99 stronglyConnCompR edges
102 (graph, vertex_fn) = graphFromEdges edges
104 decode (Node v []) | mentions_itself v = CyclicSCC [vertex_fn v]
105 | otherwise = AcyclicSCC (vertex_fn v)
106 decode other = CyclicSCC (dec other [])
108 dec (Node v ts) vs = vertex_fn v : foldr dec vs ts
109 mentions_itself v = v `elem` (graph ! v)
112 %************************************************************************
116 %************************************************************************
121 type Table a = Array Vertex a
122 type Graph = Table [Vertex]
123 type Bounds = (Vertex, Vertex)
124 type Edge = (Vertex, Vertex)
128 vertices :: Graph -> [Vertex]
131 edges :: Graph -> [Edge]
132 edges g = [ (v, w) | v <- vertices g, w <- g!v ]
134 mapT :: (Vertex -> a -> b) -> Table a -> Table b
135 mapT f t = array (bounds t) [ ARR_ELT v (f v (t!v)) | v <- indices t ]
137 buildG :: Bounds -> [Edge] -> Graph
138 #ifdef REALLY_HASKELL_1_3
139 buildG bounds edges = accumArray (flip (:)) [] bounds edges
141 buildG bounds edges = accumArray (flip (:)) [] bounds [ARR_ELT k v | (k,v) <- edges]
144 transposeG :: Graph -> Graph
145 transposeG g = buildG (bounds g) (reverseE g)
147 reverseE :: Graph -> [Edge]
148 reverseE g = [ (w, v) | (v, w) <- edges g ]
150 outdegree :: Graph -> Table Int
151 outdegree = mapT numEdges
152 where numEdges v ws = length ws
154 indegree :: Graph -> Table Int
155 indegree = outdegree . transposeG
162 => [(node, key, [key])]
163 -> (Graph, Vertex -> (node, key, [key]))
165 = (graph, \v -> vertex_map ! v)
167 max_v = length edges - 1
168 bounds = (0,max_v) :: (Vertex, Vertex)
169 sorted_edges = sortLt lt edges
170 edges1 = zipWith ARR_ELT [0..] sorted_edges
172 graph = array bounds [ARR_ELT v (mapMaybe key_vertex ks) | ARR_ELT v (_, _, ks) <- edges1]
173 key_map = array bounds [ARR_ELT v k | ARR_ELT v (_, k, _ ) <- edges1]
174 vertex_map = array bounds edges1
176 (_,k1,_) `lt` (_,k2,_) = case k1 `cmp` k2 of { LT_ -> True; other -> False }
178 -- key_vertex :: key -> Maybe Vertex
179 -- returns Nothing for non-interesting vertices
180 key_vertex k = find 0 max_v
184 find a b = case cmp k (key_map ! mid) of
185 LT_ -> find a (mid-1)
187 GT_ -> find (mid+1) b
189 mid = (a + b) `div` 2
192 %************************************************************************
196 %************************************************************************
199 data Tree a = Node a (Forest a)
200 type Forest a = [Tree a]
202 mapTree :: (a -> b) -> (Tree a -> Tree b)
203 mapTree f (Node x ts) = Node (f x) (map (mapTree f) ts)
207 instance Show a => Show (Tree a) where
208 showsPrec p t s = showTree t ++ s
210 showTree :: Show a => Tree a -> String
211 showTree = drawTree . mapTree show
213 showForest :: Show a => Forest a -> String
214 showForest = unlines . map showTree
216 drawTree :: Tree String -> String
217 drawTree = unlines . draw
219 draw (Node x ts) = grp this (space (length this)) (stLoop ts)
220 where this = s1 ++ x ++ " "
222 space n = take n (repeat ' ')
225 stLoop [t] = grp s2 " " (draw t)
226 stLoop (t:ts) = grp s3 s4 (draw t) ++ [s4] ++ rsLoop ts
228 rsLoop [t] = grp s5 " " (draw t)
229 rsLoop (t:ts) = grp s6 s4 (draw t) ++ [s4] ++ rsLoop ts
231 grp fst rst = zipWith (++) (fst:repeat rst)
233 [s1,s2,s3,s4,s5,s6] = ["- ", "--", "-+", " |", " `", " +"]
237 %************************************************************************
239 %* Depth first search
241 %************************************************************************
244 type Set s = MutableArray s Vertex Bool
246 mkEmpty :: Bounds -> ST s (Set s)
247 mkEmpty bnds = newArray bnds False
249 contains :: Set s -> Vertex -> ST s Bool
250 contains m v = readArray m v
252 include :: Set s -> Vertex -> ST s ()
253 include m v = writeArray m v True
257 dff :: Graph -> Forest Vertex
258 dff g = dfs g (vertices g)
260 dfs :: Graph -> [Vertex] -> Forest Vertex
261 dfs g vs = prune (bounds g) (map (generate g) vs)
263 generate :: Graph -> Vertex -> Tree Vertex
264 generate g v = Node v (map (generate g) (g!v))
266 prune :: Bounds -> Forest Vertex -> Forest Vertex
267 prune bnds ts = runST (mkEmpty bnds `thenST` \m ->
270 chop :: Set s -> Forest Vertex -> ST s (Forest Vertex)
271 chop m [] = returnST []
272 chop m (Node v ts : us)
273 = contains m v `thenStrictlyST` \visited ->
277 include m v `thenStrictlyST` \_ ->
278 chop m ts `thenStrictlyST` \as ->
279 chop m us `thenStrictlyST` \bs ->
280 returnST (Node v as : bs)
284 %************************************************************************
288 %************************************************************************
290 ------------------------------------------------------------
291 -- Algorithm 1: depth first search numbering
292 ------------------------------------------------------------
295 --preorder :: Tree a -> [a]
296 preorder (Node a ts) = a : preorderF ts
298 preorderF :: Forest a -> [a]
299 preorderF ts = concat (map preorder ts)
301 preOrd :: Graph -> [Vertex]
302 preOrd = preorderF . dff
304 tabulate :: Bounds -> [Vertex] -> Table Int
305 tabulate bnds vs = array bnds (zipWith ARR_ELT vs [1..])
307 preArr :: Bounds -> Forest Vertex -> Table Int
308 preArr bnds = tabulate bnds . preorderF
312 ------------------------------------------------------------
313 -- Algorithm 2: topological sorting
314 ------------------------------------------------------------
317 --postorder :: Tree a -> [a]
318 postorder (Node a ts) = postorderF ts ++ [a]
320 postorderF :: Forest a -> [a]
321 postorderF ts = concat (map postorder ts)
323 postOrd :: Graph -> [Vertex]
324 postOrd = postorderF . dff
326 topSort :: Graph -> [Vertex]
327 topSort = reverse . postOrd
331 ------------------------------------------------------------
332 -- Algorithm 3: connected components
333 ------------------------------------------------------------
336 components :: Graph -> Forest Vertex
337 components = dff . undirected
339 undirected :: Graph -> Graph
340 undirected g = buildG (bounds g) (edges g ++ reverseE g)
344 -- Algorithm 4: strongly connected components
347 scc :: Graph -> Forest Vertex
348 scc g = dfs g (reverse (postOrd (transposeG g)))
352 ------------------------------------------------------------
353 -- Algorithm 5: Classifying edges
354 ------------------------------------------------------------
357 tree :: Bounds -> Forest Vertex -> Graph
358 tree bnds ts = buildG bnds (concat (map flat ts))
360 flat (Node v rs) = [ (v, w) | Node w us <- ts ] ++
363 back :: Graph -> Table Int -> Graph
364 back g post = mapT select g
365 where select v ws = [ w | w <- ws, post!v < post!w ]
367 cross :: Graph -> Table Int -> Table Int -> Graph
368 cross g pre post = mapT select g
369 where select v ws = [ w | w <- ws, post!v > post!w, pre!v > pre!w ]
371 forward :: Graph -> Graph -> Table Int -> Graph
372 forward g tree pre = mapT select g
373 where select v ws = [ w | w <- ws, pre!v < pre!w ] \\ tree!v
377 ------------------------------------------------------------
378 -- Algorithm 6: Finding reachable vertices
379 ------------------------------------------------------------
382 reachable :: Graph -> Vertex -> [Vertex]
383 reachable g v = preorderF (dfs g [v])
385 path :: Graph -> Vertex -> Vertex -> Bool
386 path g v w = w `elem` (reachable g v)
390 ------------------------------------------------------------
391 -- Algorithm 7: Biconnected components
392 ------------------------------------------------------------
395 bcc :: Graph -> Forest [Vertex]
396 bcc g = (concat . map bicomps . map (label g dnum)) forest
398 dnum = preArr (bounds g) forest
400 label :: Graph -> Table Int -> Tree Vertex -> Tree (Vertex,Int,Int)
401 label g dnum (Node v ts) = Node (v,dnum!v,lv) us
402 where us = map (label g dnum) ts
403 lv = minimum ([dnum!v] ++ [dnum!w | w <- g!v]
404 ++ [lu | Node (u,du,lu) xs <- us])
406 bicomps :: Tree (Vertex,Int,Int) -> Forest [Vertex]
407 bicomps (Node (v,dv,lv) ts)
408 = [ Node (v:vs) us | (l,Node vs us) <- map collect ts]
410 collect :: Tree (Vertex,Int,Int) -> (Int, Tree [Vertex])
411 collect (Node (v,dv,lv) ts) = (lv, Node (v:vs) cs)
412 where collected = map collect ts
413 vs = concat [ ws | (lw, Node ws us) <- collected, lw<dv]
414 cs = concat [ if lw<dv then us else [Node (v:ws) us]
415 | (lw, Node ws us) <- collected ]