(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.


In reply to Re: directory listing to array tree by Fletch
in thread directory listing to array tree by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.