Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building the directory tree

Tags:

clojure

I am trying to build a directory tree such as how xml trees are represented, in the form of a vector, i can traverse the file system fine using the following snippet but i can't put my head around how to build a tree structure out of this?


(defn trav [dir]
  (if (.isDirectory dir)
    (do
      (println (.getName dir))
      (doseq [file (.listFiles dir)]
        (if (.isDirectory file)
          (trav file)))      
      )))
like image 318
Hamza Yerlikaya Avatar asked Dec 14 '22 01:12

Hamza Yerlikaya


2 Answers

I'm not really good at this either, but...

were you aware that there is already a "built in" function to turn a directory tree into a sequence?

See http://richhickey.github.com/clojure/clojure.core-api.html#clojure.core/file-seq .

Maybe this will meet your needs. Otherwise, we'll just wait until the really smart Clojurians show up.

like image 99
Carl Smotricz Avatar answered Jan 25 '23 07:01

Carl Smotricz


How about this?

(defstruct file :file)
(defstruct dir :file :contents)

(defn file-tree
  [#^File file]
  (if (.isDirectory file)
    (struct dir file (vec (map file-tree (.listFiles file))))
    (struct file file)))

If you query the resulting map for :file you get the file entry for this node back. If you ask for :contents and get nil, it's a file. A vector indicates a directory.

As Carl already said: maybe file-seq is more appropriate.

like image 39
kotarak Avatar answered Jan 25 '23 08:01

kotarak