递归函数错误/尝试查找给定目录的所有子目录

时间:2016-05-27 19:17:26

标签: haskell recursion functional-programming

我试图编写一个返回给定目录的所有子目录的函数(递归)。

到目前为止我所拥有的是:

String a[] = new String[]{"Hello.jpg","Goodbye.mp4","Free.xlsx","GettingStarted","File.81723.domain.8080.pdf"};
for (String s : a) {
if (s.matches(".*\\.[^.]+"))
    System.out.println(s + ": true");
else
    System.out.println(s + ": false");
}

这似乎有效。但是递归有问题 - 我想摆脱import System.Directory import Control.Monad import Data.List getSubDirs :: FilePath -> IO [FilePath] getSubDirs dir = getDirectoryContents dir >>= filterM (\x -> return $ x /= "." && x /= "..") >>= mapM (makeAbsolute . (\x -> dir ++ "/" ++ x)) >>= filterM doesDirectoryExist >>= return . reverse getDirTree :: [FilePath] -> IO [FilePath] getDirTree [] = return [] getDirTree l@(x:xs) = do a <- getSubDirs x >>= getDirTree b <- getDirTree xs return (nub $ l ++ a ++ b) 中的nub

2 个答案:

答案 0 :(得分:1)

这看起来不对:

l

最后一行添加了x:xs b l getDirTree xsb调用中包含xs参数,因此{{1}将包含xs。因此,return ( x : a ++ b )被包含两次(在每个递归步骤!)。

请尝试{{1}}。

答案 1 :(得分:1)

这似乎有效:

getDirTree' :: FilePath -> IO [FilePath]
getDirTree' path = do
  subs <- getSubDirs path
  as <- mapM getDirTree' subs
  return $ subs ++ concat as
相关问题