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
200_success
145k22 gold badges190 silver badges478 bronze badges
asked May 11, 2016 at 21:42
\$\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.

answered Jun 23, 2016 at 3:57
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.