tags:

views:

96

answers:

2

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)))      
      )))
+6  A: 

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.

Carl Smotricz
+4  A: 

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.

kotarak