Hi,

On 21 Feb., 08:17, Damien <[email protected]> wrote:

> Not sure if I should talk about flattening but basically I'm trying to
> achieve the following transformation:
>
> user=>(flatten-tree {1 {2 {3 4 5 6} 7 {8 9}}})
> ((1 2 3 4) (1 2 5 6) (1 7 8 9))

Using protocols seems overkill:

(defprotocol TreeFlattener (flatten-tree [this]))

(extend-protocol TreeFlattener
  clojure.lang.IPersistentMap
  (flatten-tree
    [this]
    (mapcat (fn [[k v]] (map #(cons k %) (flatten-tree v))) this))
  Object
  (flatten-tree
    [this]
    (list (list this)))
  nil
  (flatten-tree [_] (list (list nil))))

user=> (flatten-tree {1 {2 {3 [4 nil] 5 6} 7 {8 9}}})
((1 2 3 [4 nil]) (1 2 5 6) (1 7 8 9))

... but it also allows to add other data structures later on:

(extend-type clojure.lang.IPersistentVector
  TreeFlattener
  (flatten-tree
    [this]
    (mapcat (fn [idx x] (map #(cons idx %) (flatten-tree x))) (range)
this)))

user=> (flatten-tree {1 {2 {3 [4 nil] 5 6} 7 {8 9}}})
((1 2 3 0 4) (1 2 3 1 nil) (1 2 5 6) (1 7 8 9))

Beware structure depths and stack overflows, though.

Hope that helps.

Sincerely
Meikel

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to