我正在尝试使用Haskell进行目录结构的递归下降。我希望只在需要时(惰性地)检索子目录和文件。
我编写了以下代码,但当我运行它时,跟踪显示所有目录都在第一个文件之前被访问:
module Main where
import Control.Monad ( forM, forM_, liftM )
import Debug.Trace ( trace )
import System.Directory ( doesDirectoryExist, getDirectoryContents )
import System.Environment ( getArgs )
import System.FilePath ( (</>) )
-- From Real World Haskell, p. 214
getRecursiveContents :: FilePath -> IO [FilePath]
getRecursiveContents topPath = do
names <- getDirectoryContents topPath
let
properNames =
filter (`notElem` [".", ".."]) $
trace ("Processing " ++ topPath) names
paths <- forM properNames $ \name -> do
let path = topPath </> name
isDirectory <- doesDirectoryExist path
if isDirectory
then getRecursiveContents path
else return [path]
return (concat paths)
main :: IO ()
main = do
[path] <- getArgs
files <- getRecursiveContents path
forM_ files $ \file -> putStrLn $ "Found file " ++ file
我如何在下降过程中与文件处理交错进行?问题是在main
函数中的forM_
之后执行files <- getRecursiveContents path
动作吗?
getRecursiveContents
。我没有看到后面的部分。我会去看一下。谢谢。 - Ralph