Skip to content

Instantly share code, notes, and snippets.

@edw
Last active November 12, 2021 20:31
Show Gist options
  • Save edw/5128978 to your computer and use it in GitHub Desktop.
Save edw/5128978 to your computer and use it in GitHub Desktop.
To delete a directory recursively in Clojure.
(defn delete-recursively [fname]
(let [func (fn [func f]
(when (.isDirectory f)
(doseq [f2 (.listFiles f)]
(func func f2)))
(clojure.java.io/delete-file f))]
(func func (clojure.java.io/file fname))))
@aaronblenkush
Copy link

aaronblenkush commented Jun 28, 2019

Just for fun, here's one that is tail recursive. The fs arg will act as the stack instead of the thread stack, growing as it traverses the file structure in a depth-first post-order search:

(defn tail-recursive-delete
  [& fs]
  (when-let [f (first fs)]
    (if-let [cs (seq (.listFiles (io/file f)))]
      (recur (concat cs fs))
      (do (io/delete-file f)
          (recur (rest fs))))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment