2
\$\begingroup\$

This code works, but I want to refine it:

# =======================
# Dir Walk
#
# This will recursively walk a directory
# ========================

function dirwalk(path::AbstractString, fn::Function)
  content = readdir(path)
  for c in content
    p = joinpath(path, c)
    if isdir(p)
      dirwalk(p, fn)
    elseif isfile(p)
      fn(p)
    end
  end
end
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

First, use a docstring instead of a comment:

"""Recursively walk a directory."""
function [ . . . ]

Using a docstring allows Julia's built-in help features to work with your function.

Next, I would recommend putting the function argument first:

function dirwalk(fn::Function, path::AbstractString)

Why? This allows dirwalk to be used with Julia's do block syntax:

dirwalk("path/to/file") do p
    # do stuff with p, the path
end

which is often nicer than using anonymous function syntax.

Now for the function itself, you don't need a temporary variable to store content. This:

for c in readdir(path)

is shorter and reads just as well. Inside the loop, things generally look fine (except the order of dirwalk could be reversed). Note that your implementation ignores symlinks, which are neither directories nor regular files.

As for style, the Julia style guide recommends 4-space indenting. Some projects use 2-space indenting, however, and that is a personal decision.

Finally, you might be interested in the walkdir function.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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