Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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))))
@artekcs

This comment has been minimized.

Copy link

commented Apr 8, 2015

Fantastic. This is very useful on Windows when you can't delete insane directory hierarchies because of the MAX_PATH limitation. Just fire a "lein repl", load your script and (delete-recursively "insane/path").
Thanks a lot

@LouisBurke

This comment has been minimized.

Copy link

commented Sep 4, 2016

Brilliant.

@erdos

This comment has been minimized.

Copy link

commented Jan 3, 2017

this does the same using the build-in file-seq function to enumerate the contents of the directory.

(defn delete-recursively [fname]
  (doseq [f (reverse (file-seq (clojure.java.io/file fname)))]
     (clojure.java.io/delete-file f)))
@ulsa

This comment has been minimized.

Copy link

commented May 18, 2017

It's elegant, but I'm not sure it's as robust for large trees as the recursive version. reverse removes the laziness of file-seq.

@ignorabilis

This comment has been minimized.

Copy link

commented Oct 18, 2017

Using letfn will simplify things a bit (no need for (func func )). Also you can expose the silently argument:

(defn delete-files-recursively [fname & [silently]]
  (letfn [(delete-f [file]
            (when (.isDirectory file)
              (doseq [child-file (.listFiles file)]
                (delete-f child-file)))
            (clojure.java.io/delete-file file silently))]
    (delete-f (clojure.java.io/file fname))))
@leontalbot

This comment has been minimized.

Copy link

commented Nov 22, 2018

Nice, thanks for sharing!

@kyptin

This comment has been minimized.

Copy link

commented Dec 9, 2018

You can remove the 'pass a function to itself' weirdness without letfn. The fn form supports a name before the parameter list. For example, ((fn fact [n] (if (zero? n) 1 (* n (fact (dec n))))) 5) returns 120.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.