Tuesday, 15 March 2011

clojure - Traversing a tree in Pre-order -



clojure - Traversing a tree in Pre-order -

i new clojure functional programming. trying traverse tree in pre-order using:

(def preordercoll []) (deftrace preorder [mytree] (if-not (empty? mytree) (do (println "position"(value mytree)) (cons (value mytree) (preorder (left-child mytree))) (cons (value mytree) (preorder (right-child mytree)))) )preordercoll) ) (preorder [45[65 [90 nil nil] [81 nil nil]] [72[82 nil nil][96 nil nil]]])

i unable append values of node in list, tried using 'conj' operation on global variable preordercoll, yes doesn't work object oriented , tried using cons, few values returned, in improper order. can guide me error making?

i thought of using partial function not find how supply value of node in recursive manner. not asking code please draw me in right direction collection of values in pre-order.

you're on right track, have nesting of cons calls little off. first note on evaluation of forms in clojure. 1 of key ideas every form evaluates something* why there no "return" statement in language, because homecoming statement what's point in having it. in case of do look homecoming value of look lastly statement so:

(do 1 2 3)

returns (evaluates to) 3. in do look in code returns result of sec cons, , first cons has no effect.

(do (println "position"(value mytree)) (cons (value mytree) (preorder (left-child mytree))) ;; <-- nil (cons (value mytree) (preorder (right-child mytree))))

instead sounds similar look starts result of calling preorder on left tree, concatinates result of calling preorder on right tree, attaches current node's value front end of that.

(let [left-side (preorder (left-child mytree)) right-side (preorder (left-child mytree)) this-value (value mytree)] (do (println "position" this-value) (cons this-value (concat right-side left-side))

*(for pedants) "except ignore reader maco #_"

clojure functional-programming

No comments:

Post a Comment