我想枚举Haskell中某个文件夹的所有子文件夹。获取所有文件夹内容很容易,有一个getDirectoryContents函数。但是我该如何过滤它们呢?因为getDirectoryContents返回一个IO [FilePath],而filter需要[a],所以我不能直接把这两个放在一起。(显然,我是一条有单数和do-notation的新鲜鱼。)
getAllFolders :: FilePath -> IO [FilePath]
getAllFolder path = do
allItems <- getDirectoryContents path
-- now what? the predicate is doesDirectoryExist发布于 2013-05-23 22:27:00
getAllFolders path = do
contents <- getDirectoryContents path
-- do something with contents now, it's a plain [FilePath]问题是谓词doesDirectoryExist的类型是FilePath -> IO Bool。对于这样的事情,有
ghci> :t Control.Monad.filterM
Control.Monad.filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]Control.Monad中定义的filterM,因此
getAllFolders path = do
contents <- getDirectoryContents path
filterM doesDirectoryExist contents或者,不将目录的内容绑定到名称,
getAllFolders path = getDirectoryContents path >>= filterM doesDirectoryExist和无指针:
getAllFolders = getDirectoryContents >=> filterM doesDirectoryExist发布于 2013-05-23 22:24:58
看起来Control.Monad提供的filterM就是答案:
getAllFolders :: FilePath -> IO [FilePath]
getAllFolders path = do
allItems <- getDirectoryContents path
justFolders <- filterM doesDirectoryExist allItems
return justFoldershttps://stackoverflow.com/questions/16716267
复制相似问题