Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a Tree in Scalaz

The Scalaz Tree class proves seemingly very useful `Zipper' functionality via TreeLoc (Javadoc).

However, it's not apparent to me how to easily iterate through a tree (e.g. to find the `k-th' node in a tree containing a total of n>k nodes) without doing a lot of conditional hedging on whether the zipper is at the end of the list of current children.

Is there an easy way to do this that I'm missing?

like image 305
NietzscheanAI Avatar asked Dec 13 '25 13:12

NietzscheanAI


1 Answers

Stealing from the TreeLoc.find method, you could do something like this:

  def findAt[A](tree: TreeLoc[A], k: Int): Option[TreeLoc[A]] = {
    Cobind[TreeLoc].cojoin(tree).tree.flatten.drop(k).headOption
  }
like image 78
Noah Avatar answered Dec 15 '25 22:12

Noah