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)

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

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.

| improve this answer | |

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.