问题
Is there some recursive directory walker in Haskell so I could write something like
listing <- walkDir "/tmp"
I would not like to write my own. I can install some dependency from cabal but I want it to be cross platform (at least Linux and Windows).
回答1:
Here is one way to list all Haskell files in a directory tree, using directory-tree that is not in a hidden directory (whose name starts with '.'):
import Data.Traversable (traverse)
import System.Directory.Tree (
AnchoredDirTree(..), DirTree(..),
filterDir, readDirectoryWith
)
import System.FilePath (takeExtension)
listFilesDirFiltered = do
_:/tree <- readDirectoryWith return "C:\\devmy\\code"
traverse print $ filterDir myPred tree
return ()
where myPred (Dir ('.':_) _) = False
myPred (File n _) = takeExtension n == ".hs"
myPred _ = True
main = listFilesDirFiltered
Works on both Windows and Linux.
回答2:
http://hackage.haskell.org/package/FilePather has that sort of recursive directory walking functionality.
回答3:
I have a recursive definition for traversing a directory using filepath package:
import Control.Monad
import System.Directory
import System.FilePath
import System.Posix.Files
-- | Traverse from 'top' directory and return all the files by
-- filtering out the 'exclude' predicate.
traverseDir :: FilePath -> (FilePath -> Bool) -> IO [FilePath]
traverseDir top exclude = do
ds <- getDirectoryContents top
paths <- forM (filter (not.exclude) ds) $ \d -> do
let path = top </> d
s <- getFileStatus path
if isDirectory s
then traverseDir path exclude
else return [path]
return (concat paths)
回答4:
The filemanip package provides powerful and elegant functions for that. For example it provides a fold function that will recursively call your function down a directory tree. As an example i used it here to recursively list files in a directory starting from the oldest
来源:https://stackoverflow.com/questions/13297896/is-there-some-directory-walker-in-haskell