tail-recursive列出给定文件位置的所有子目录

时间:2014-10-22 04:20:56

标签: scala tail-recursion

我想获取给定文件位置的所有非空目录,例如:

/src/abc
/src/abc/123/123.txt
/src/abc/abc/123.txt
/src/abc/foo/123.txt

我想获得Seq [String]

/src/abc/123
/src/abc/abc
/src/abc/foo

我使用此代码。

def getAllDirectories(location: String): Seq[String] = {

    def recursiveListDirectories(f: File): Seq[File] = {
      val these = f.listFiles
      val directories = these.filter(_.isDirectory)
      directories ++ directories.flatMap(recursiveListDirectories)
    }
    recursiveListDirectories(new File(location)).filter(t => !t.listFiles().forall(_.isDirectory)).map(_.getPath)
  }

我想知道如何使 recursiveListDirectories 方法尾递归?

非常感谢提前

1 个答案:

答案 0 :(得分:4)

设置内部函数以保留结果目录和仍需检查的目录的累积列表。尝试依次检查每个目录,将所有子目录添加到下一个调用的等待列表中。例如:

def getAllDirectories(location: String): Seq[String] = {

  def go(toCheck: List[File], results: List[File]): Seq[File] = toCheck match {
    case head :: tail =>
      val these = head.listFiles
      val directories = these.filter(_.isDirectory)
      val updated = if (these.size == directories.size) results else head :: results
      go(tail ++ directories, updated)
    case _ => results
  }

  go(new File(location) :: Nil, Nil).map(_.getPath)
}