Skip to content

Commit 6b47338

Browse files
committed
Bundle together generate, prune, and chop into dfs
1 parent 07d3d27 commit 6b47338

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed

containers/src/Data/Graph.hs

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -472,27 +472,24 @@ dff g = dfs g (vertices g)
472472
-- | A spanning forest of the part of the graph reachable from the listed
473473
-- vertices, obtained from a depth-first search of the graph starting at
474474
-- each of the listed vertices in order.
475-
dfs :: Graph -> [Vertex] -> Forest Vertex
476-
dfs g vs = prune (bounds g) (map (generate g) vs)
477-
478-
generate :: Graph -> Vertex -> Tree Vertex
479-
generate g v = Node v (map (generate g) (g!v))
480-
481-
prune :: Bounds -> Forest Vertex -> Forest Vertex
482-
prune bnds ts = run bnds (chop ts)
483-
484-
chop :: Forest Vertex -> SetM s (Forest Vertex)
485-
chop [] = return []
486-
chop (Node v ts : us)
487-
= do
488-
visited <- contains v
489-
if visited then
490-
chop us
491-
else do
492-
include v
493-
as <- chop ts
494-
bs <- chop us
495-
return (Node v as : bs)
475+
476+
-- This function deviates from King and Launchbury's implementation by
477+
-- bundling together the functions generate, prune, and chop for efficiency
478+
-- reasons.
479+
dfs :: Graph -> [Vertex] -> Forest Vertex
480+
dfs g vs0 = run (bounds g) $ go vs0
481+
where
482+
go :: [Vertex] -> SetM s (Forest Vertex)
483+
go [] = pure []
484+
go (v:vs) = do
485+
visited <- contains v
486+
if visited
487+
then go vs
488+
else do
489+
include v
490+
as <- go (g!v)
491+
bs <- go vs
492+
pure $ Node v as : bs
496493

497494
-- A monad holding a set of vertices visited so far.
498495
#if USE_ST_MONAD

0 commit comments

Comments
 (0)