Clojure create directory hierarchy - but not procedurally

Let's say I need to create the following directory structure in Clojure:

a \--b | \--b1 | \--b2 \--c \-c1 

Instead of performing procedural actions such as:

 (def a (File. "a")) (.mkdir a) (def b (File. a "b")) (.mkdir b) ;; ... 

... is there a smart way to somehow represent the above actions as data, declaratively, and then create a hierarchy in one fell swoop?

+7
source share
1 answer

A quick and easy approach would be to create a dirs vector to create and map mkdir to it:

 user> (map #(.mkdir (java.io.File. %)) ["a", "a/b" "a/b/c"]) (true true true) 

or you can specify the structure of your tree as a tree and use lightning to walk along it, creating paths on the path:

 (def dirs ["a" ["b" ["b1" "b2"]] ["c" ["c1"]]]) (defn make-dir-tree [original] (loop [loc (zip/vector-zip original)] (if (zip/end? loc) (zip/root loc) (recur (zip/next (do (if (not (vector? (zip/node loc))) (let [path (apply str (interpose "/" (butlast (map first (zip/path loc))))) name (zip/node loc)] (if (empty? path) (.mkdir (java.io.File. name)) (.mkdir (java.io.File. (str path "/" name)))))) loc)))))) (make-dir-tree dirs) 

.

 arthur@a :~/hello$ find a a a/c a/c/c1 a/b a/b/c a/b/b2 a/b/b1 

If you do a lot of general system administration, then there might be something more difficult. The Pallet Project is a library for system administration of all kinds on physical and cloud systems (although it tends to cloud things). In particular, directory

+8
source

All Articles