Is there some directory walker in Haskell?

安稳与你 提交于 2019-12-06 17:12:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!