in reply to directory listing to array tree
(ns tree-sample (:use [clojure.contrib str-utils map-utils])) (def test-paths [ "/usr/local/bin" "/var/www/data/stuff" "/var/www" "/var/www/data/misc" "/var/logs" "/var/logs/data" "/usr/fnord" ]) (defn split-path [p] (re-split #"/" p)) (defn path-to-map [p] (let [p-rev (reverse p)] (loop [hd (first p-rev) tl (rest p-rev) acc {}] (if (empty? tl) {hd acc} (recur (first tl) (rest tl) {hd acc}))))) (defn merge-trees [tl] (loop [hd (first tl) tl (rest tl) acc {}] (if (empty? tl) (deep-merge-with concat hd acc) (recur (first tl) (rest tl) (deep-merge-with concat hd acc))))) (defn printTree ([t] (printTree t 0)) ([t indent] (let [prefix (apply str (repeat indent " ")) dirs (sort (keys t))] (loop [curdir (first dirs) rd (rest dirs)] (println (if (zero? indent) "/" (str prefix "->")) curdir) (let [ch (get t curdir)] (when-not (empty? ch) (printTree ch (+ 2 indent)))) (when-not (empty? rd) (recur (first rd) (rest rd))))))) (println (str "test data:\n\t" (apply str (interpose "\n\t" test-paths +)))) (println "tree:") (printTree (merge-trees (map path-to-map (map split-path test-paths))))
Update: Tweaked to sort directory names.
Update 2: And yes, I have the Perl version (which came out about ~4 lines shorter). No, it's left as an exercise for the reader. :)
The cake is a lie.
The cake is a lie.
The cake is a lie.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: directory listing to array tree
by ELISHEVA (Prior) on Sep 14, 2009 at 19:29 UTC | |
by ikegami (Patriarch) on Sep 14, 2009 at 19:53 UTC | |
by Fletch (Bishop) on Sep 14, 2009 at 20:48 UTC |