3
\$\begingroup\$

I'm new to Scala, and would appreciate any notes about a better approach, correctness, or style.

/**
 * Call proc(f) for each file in the directory tree rooted at dir.
 * 
 * proc will not be called for directories, just for files.
 */
def traverse(dir: File, proc: File => Unit): Unit = {
    dir.listFiles foreach { (f) => {
            if(f.isDirectory) {
                traverse(f, proc)
            } else {
                proc(f)
            }
        }
    }
}
\$\endgroup\$
3
\$\begingroup\$

Your code is fine. Nevertheless, removing unnecessary braces can increase readability:

def traverse(dir: File, proc: File => Unit): Unit =
  dir.listFiles foreach { f => if (f.isDirectory) traverse(f, proc) else proc(f) }
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

I prefer something like this:

def traverse(root: File): Iterator[File] =
  if (root.isDirectory)
    root.listFiles.iterator.map(traverse).fold(Seq(root).iterator)(_ ++ _)
  else
    Seq(root).iterator

You can use that iterator with a foreach (as you are doing), but you get a lot more of flexibility, you can do map, filter, and all the usual Scala awesomeness very easily. For example, this is what you were doing

  def whatever(root:File, proc:File => Unit) = traverse(root) foreach proc

There may be more efficient (@tailrec maybe), lazy or better options. I'd be interested in seeing them, this was just the most immediate solution I could think of to put an example.

PD: this doesn't filter the files that are directories, you can impose that constraint with something of the form:

def traverse(root: File): Iterator[File] =
  if (root.isDirectory)
    root.listFiles.iterator map traverse reduce (_ ++ _)
  else
    Seq(root).iterator

But I'd suggest not to do that.

PD: perhaps the signature should be something like:

def toTraversable(root:File): Traversable[File]

Maybe its in the standard Scala API already...

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.