如何打印递归调用堆栈

时间:2015-01-12 21:57:49

标签: scala recursion

在下面的代码中,我试图打印递归函数depth的调用堆栈:

sealed trait Tree[+A]
case class Leaf[A](value: A) extends Tree[A]
case class Branch[A](left: Tree[A], right: Tree[A]) extends Tree[A]

val l1 = Leaf(1)           //> l1  : trees.Leaf[Int] = Leaf(1)
val b1 = Branch(l1, l1)    //> b1  : trees.Branch[Int] = Branch(Leaf(1),Leaf(1))
val b2 = Branch(b1, l1)    //> b2  : trees.Branch[Int] = Branch(Branch(Leaf(1),Leaf(1)),Leaf(1))

def size[A](t: Tree[A]): Int = t match {
  case Leaf(_) => 1
  case Branch(l, r) => 1 + size(l) + size(r)
}                          //> size: [A](t: trees.Tree[A])Int

def depth[A](t: Tree[A]): Int = t match {
  case Leaf(_) =>
  {
    print(" + 0")
    0
  }
  case Branch(l, r) =>
  {
    val d1 = depth(l)
    val d2 = depth(r)
    print(" + 1 + ("+d1 +" max "+d2+")")
    1 + (d1 max d2)
  }
}                          //> depth: [A](t: trees.Tree[A])Int


println("\n"+depth(b2))    //>  + 0 + 0 + 1 + (0 max 0) + 0 + 1 + (1 max 0)
                           //| 2

这不正确://> + 0 + 0 + 1 +(0最大0)+ 0 + 1 +(1最大0)

是否存在打印递归函数的调用堆栈或如何打印上述depth函数的调用堆栈的通用方法?

depth函数返回树的最大路径长度。

1 个答案:

答案 0 :(得分:0)

def depth[A](t: Tree[A]): Int = t match {
  case Leaf(_) =>
    print("0")
    0
  case Branch(l, r) =>
    print("1 + (")
    val d1 = depth(l)
    print(" max ")
    val d2 = depth(r)
    print(")")
    1 + (d1 max d2)
}

这会为您的示例打印1 + (1 + (0 max 0) max 0)