Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tree traversal with corecursion

I'm trying to figure out corecursion in Clojure with nontrivial (i.e. not Fibonacci), but manageable, examples. Apparently it is possible to implement binary tree traversal with corecursion. Wikipedia has an example in Python which I am unable to understand.

How can I implement it in Clojure? Let's say I'm looking for BFS, but it could be any order.

Here's what I have so far:

(defstruct tree :val :left :right)

(def my-tree (struct tree 1 (struct tree 2) (struct tree 3 4 5)))

(def bfs (lazy-cat [my-tree] (map #(:left %) bfs) (map #(:right %) bfs) ))

(println (take 4 bfs))

Unfortunately it seems to be going all the way to the left, ignoring the right branch.

like image 824
Konrad Garus Avatar asked Jul 22 '10 19:07

Konrad Garus


1 Answers

Assuming Michal's code does what you want, this also works:

(defn bftrav [& trees]
  (when trees
    (concat trees 
      (->> trees
        (mapcat #(vector (:left %) (:right%)))
        (filter identity)
        (apply bftrav)))))
like image 166
Alex Taggart Avatar answered Oct 03 '22 23:10

Alex Taggart