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
前にアクションが実行されるという問題はありますか?forM_
main