【问题标题】:How to print recursive call stack如何打印递归调用堆栈
【发布时间】:2015-01-12 21:57:49
【问题描述】:

在下面的代码中,我试图打印递归函数 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 max 0) + 0 + 1 + (1 max 0)

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

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

【问题讨论】:

    标签: scala recursion


    【解决方案1】:
    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)

    【讨论】:

      猜你喜欢
      • 2016-09-27
      • 2023-03-15
      • 1970-01-01
      • 2010-11-28
      • 2015-08-25
      • 2019-09-30
      • 2010-11-23
      • 2020-09-02
      • 1970-01-01
      相关资源
      最近更新 更多