Skip to content

Instantly share code, notes, and snippets.

@duese
Created August 13, 2016 23:13
Show Gist options
  • Save duese/9274638f5f329c35a8f3a88d3215c918 to your computer and use it in GitHub Desktop.
Save duese/9274638f5f329c35a8f3a88d3215c918 to your computer and use it in GitHub Desktop.
Tree parsing with tailrec recursive method
import scala.annotation.tailrec
class Item(name: String) {
override def toString: String = name
}
class Group(name: String, items: List[Item]) extends Item(name) {
def size: Int = items.size
def get(i: Int): Item = items(i)
}
// Build up a tree:
// |
// g0
// / \
// g1 g2------g3
// / / \ / \
// a b e c d
//
val a = new Item("a")
val b = new Item("b")
val c = new Item("c")
val d = new Item("d")
val e = new Item("e")
val g3 = new Group("3", List(c, d))
val g2 = new Group("2", List(g3, b, e))
val g1 = new Group("1", List(a))
val g0 = new Group("0", List(g1, g2))
def findItems(item: Item): List[Item] = {
@tailrec
def findItems(startItems: List[Item], resultCache: List[Item]): List[Item] = {
startItems match {
case List() =>
resultCache
case (head: Group) :: tail =>
val list: List[Item] = (
for (i <- 0 until head.size) yield head.get(i)
).toList
findItems(list ::: tail, head :: resultCache)
case (head: Item) :: tail =>
findItems(tail, head :: resultCache)
}
}
findItems(List(item), List.empty)
}
val result = findItems(g0)
result.foreach { item => println(s"- Item: $item") }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment