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.
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)))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With