【发布时间】:2012-12-24 22:01:16
【问题描述】:
我正在尝试使用 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
如何将文件处理与下降交错?是files <- getRecursiveContents path动作在main中的下面forM_之前执行的问题吗?
【问题讨论】:
-
Real World Haskell 的"Searching the filesystem" 章节中称为“查看遍历的另一种方式”的后面部分还提供了一种更灵活的文件系统导航方式,该方式使用折叠和迭代器。
-
我(显然)从 RWH 获取了函数
getRecursiveContents。我没有看到后面的部分。我会看看。谢谢。
标签: lazy-evaluation directory-structure haskell