【发布时间】:2012-09-26 21:35:20
【问题描述】:
我尝试遍历目录树。幼稚的深度优先遍历似乎不会以惰性方式生成数据并且会耗尽内存。接下来我尝试了一种广度优先的方法,它显示了同样的问题 - 它使用了所有可用的内存,然后崩溃了。
我的代码是:
getFilePathBreadtFirst :: FilePath -> IO [FilePath]
getFilePathBreadtFirst fp = do
fileinfo <- getInfo fp
res :: [FilePath] <- if isReadableDirectory fileinfo
then do
children <- getChildren fp
lower <- mapM getFilePathBreadtFirst children
return (children ++ concat lower)
else return [fp] -- should only return the files?
return res
getChildren :: FilePath -> IO [FilePath]
getChildren path = do
names <- getUsefulContents path
let namesfull = map (path </>) names
return namesfull
testBF fn = do -- crashes for /home/frank, does not go to swap
fps <- getFilePathBreadtFirst fn
putStrLn $ unlines fps
我认为所有代码都是线性或尾递归的,我希望文件名列表立即开始,但实际上并非如此。我的代码和我的想法中的错误在哪里?我在哪里丢失了惰性评估?
【问题讨论】:
标签: haskell