tags:

views:

327

answers:

4

What would be a idiomatic way to represent a tree in Clojure?

     A
    / \
   B   C
  /\    \
 D  E    F

Such as the one above, performance is not important and tree's wont grow more than 1k elements.

+3  A: 

There's a scary way of doing it using just cons:

(defn mktree 
  ([label l r] (cons label (cons l r))) 
  ([leaf] (cons leaf (cons nil nil))))
(defn getlabel [t] (first t))
(defn getchildren [t] (rest t))
(defn getleft [t] (first (getchildren t)))
(defn getright [t] (rest (getchildren t)))

Note that children isn't a list; it's a pair. If your trees aren't just binary, you could make it a list. use nil when there's no left or right child, of course.

Otherwise, see this answer.

The tree in your picture:

(mktree 'A (mktree 'B (mktree 'D) (mktree 'E)) (mktree 'C nil (mktree 'F)))
wrang-wrang
Hamza Yerlikaya
thanks ;) common lisp has both. i'll edit. it does have 'cons' though?
wrang-wrang
I think you should edit it to say "I only know common lisp". Common Lisp is not 'Lisp'. It's *a* Lisp.
Rayne
A: 

You should probably use a struct for this.

(defstruct bintree :left :right :key)

You can use struct-map to instantiate the structure.

(struct-map bintree :left nil :right nil :key 0)
Rayne
A: 

Tree's underly just about everything in clojure because they lend them selves so nicely to structural sharing in persistent data structure. Maps and Vectors are actually trees with a high brancing factor to give them bounded lookup and insert time. so the shortest answer i can give (though its not really that useful) is I really recommend Purely functional data structures by Chris Okasaki for a real answer to this question. also Rich Hicky's video on clojure data ctructures on blip.tv

(set 'A 'B 'C)
Arthur Ulfeldt
+2  A: 
'(A (B (D) (E)) (C (F)))
Dan