如何打印递归调用堆栈
How to print recursive call stack
在下面的代码中,我试图打印递归函数的调用堆栈 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
函数的调用堆栈?
深度函数returns一棵树的最大路径长度。
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)
。
在下面的代码中,我试图打印递归函数的调用堆栈 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
函数的调用堆栈?
深度函数returns一棵树的最大路径长度。
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)
。