flatten tools

11 views
Skip to first unread message

kyle smith

unread,
Jul 10, 2009, 9:08:56 AM7/10/09
to Clojure
I wrote these and thought they might be useful. Feel free to add them
to clojure.contrib.seq-utils

(defn flatten-n [n coll]
"Like flatten, but only goes n levels deep."
(if (= n 0)
coll
(recur (dec n) (apply concat (map #(if (sequential? %) % (list %))
coll)))))

(defn- unflatten* [tree coll]
(loop [val-tree []
new-tree tree
new-coll coll]
(if (nil? (first new-tree))
[val-tree new-coll]
(if (sequential? (first new-tree))
(let [[a b] (unflatten* (first new-tree) new-coll)]
(recur (conj val-tree a) (next new-tree) b))
(recur (conj val-tree (first new-coll)) (next new-tree) (next new-
coll))))))

(defn unflatten [tree coll]
"Returns a new tree with the same shape as tree containing the
elements of coll.
coll must be of length #leaves of tree"
(first (unflatten* tree coll)))


user> (unflatten [[1] [2 3] 4 [5 [6]] 7] '[a b c d e f g])
[[a] [b c] d [e [f]] g]
Reply all
Reply to author
Forward
0 new messages