如何使树映射尾部递归?

Mic*_*ael 7 tree recursion functional-programming scala tail-recursion

假设我有一个像这样的树数据结构:

trait Node { val name: String }
case class BranchNode(name: String, children: List[Node]) extends Node
case class LeafNode(name: String) extends Node
Run Code Online (Sandbox Code Playgroud)

假设我还有一个映射叶子的函数:

def mapLeaves(root: Node, f: LeafNode => LeafNode): Node = root match {
  case ln: LeafNode => f(ln)
  case bn: BranchNode => BranchNode(bn.name, bn.children.map(ch => mapLeaves(ch, f)))
}
Run Code Online (Sandbox Code Playgroud)

现在,我正在尝试使此函数尾部递归,但是很难弄清楚该怎么做。我已经读过这个答案,但仍然不知道使该二叉树解决方案适用于多路树。

您将如何重写mapLeaves以使其尾部递归?

And*_*kin 7

“调用栈”和“递归”只是流行的设计模式,后来被并入大多数编程语言中(因此大部分变为“不可见”)。没有什么可以阻止您使用堆数据结构来重新实现两者。因此,这是“明显的” 1960年代TAOCP复古风格的解决方案:

trait Node { val name: String }
case class BranchNode(name: String, children: List[Node]) extends Node
case class LeafNode(name: String) extends Node

def mapLeaves(root: Node, f: LeafNode => LeafNode): Node = {
  case class Frame(name: String, mapped: List[Node], todos: List[Node])
  @annotation.tailrec
  def step(stack: List[Frame]): Node = stack match {
    // "return / pop a stack-frame"
    case Frame(name, done, Nil) :: tail => {
      val ret = BranchNode(name, done.reverse)
      tail match {
        case Nil => ret
        case Frame(tn, td, tt) :: more => {
          step(Frame(tn, ret :: td, tt) :: more)
        }
      }
    }
    case Frame(name, done, x :: xs) :: tail => x match {
      // "recursion base"
      case l @ LeafNode(_) => step(Frame(name, f(l) :: done, xs) :: tail)
      // "recursive call"
      case BranchNode(n, cs) => step(Frame(n, Nil, cs) :: Frame(name, done, xs) :: tail)
    }
    case Nil => throw new Error("shouldn't happen")
  }
  root match {
    case l @ LeafNode(_) => f(l)
    case b @ BranchNode(n, cs) => step(List(Frame(n, Nil, cs)))
  }
}
Run Code Online (Sandbox Code Playgroud)

尾递归step函数采用带有“堆栈框架”的经过优化的堆栈。“堆栈框架”存储当前正在处理的分支节点的名称,已处理的子节点的列表以及以后仍必须处理的其余节点的列表。这大致对应于递归mapLeaves函数的实际堆栈框架。

有了这个数据结构,

  • 从递归调用返回对应于解构一个Frame对象,或者返回最终结果,或者至少stack缩短一帧。
  • 递归调用对应于将a附加Framestack
  • 基本案例(f在叶子上调用)不会创建或删除任何框架

一旦了解了如何显式表示通常不可见的堆栈框架,该转换就很简单,而且大多是机械的。

例:

val example = BranchNode("x", List(
  BranchNode("y", List(
    LeafNode("a"),
    LeafNode("b")
  )),
  BranchNode("z", List(
    LeafNode("c"),
    BranchNode("v", List(
      LeafNode("d"),
      LeafNode("e")
    ))
  ))
))

println(mapLeaves(example, { case LeafNode(n) => LeafNode(n.toUpperCase) }))
Run Code Online (Sandbox Code Playgroud)

输出(缩进):

BranchNode(x,List(
  BranchNode(y,List(
    LeafNode(A),
    LeafNode(B)
  )),
  BranchNode(z, List(
    LeafNode(C),
    BranchNode(v,List(
      LeafNode(D),
      LeafNode(E)
    ))
  ))
))
Run Code Online (Sandbox Code Playgroud)


Krz*_*sik 6

使用称为trampoline的技术来实现它可能会更容易。如果使用它,您将能够使用两个函数进行相互递归调用(使用tailrec,您只能使用一个函数)。与tailrec此类似,此递归将转换为纯循环。

蹦床是在美国Scala标准库中实现的scala.util.control.TailCalls

import scala.util.control.TailCalls.{TailRec, done, tailcall}

def mapLeaves(root: Node, f: LeafNode => LeafNode): Node = {

  //two inner functions doing mutual recursion

  //iterates recursively over children of node
  def iterate(nodes: List[Node]): TailRec[List[Node]] = {
     nodes match {
       case x :: xs => tailcall(deepMap(x)) //it calls with mutual recursion deepMap which maps over children of node 
         .flatMap(node => iterate(xs).map(node :: _)) //you can flat map over TailRec
       case Nil => done(Nil)
     }
  }

  //recursively visits all branches
  def deepMap(node: Node):  TailRec[Node] = {
    node match {
      case ln: LeafNode => done(f(ln))
      case bn: BranchNode => tailcall(iterate(bn.children))
         .map(BranchNode(bn.name, _)) //calls mutually iterate
    }
  }

  deepMap(root).result //unwrap result to plain node
}
Run Code Online (Sandbox Code Playgroud)

相反,TailCalls您也可以使用Evalfrom CatsTrampolinefrom scalaz

使用该实现功能可以毫无问题地工作:

def build(counter: Int): Node = {
  if (counter > 0) {
    BranchNode("branch", List(build(counter-1)))
  } else {
    LeafNode("leaf")
  }
}

val root = build(4000)

mapLeaves(root, x => x.copy(name = x.name.reverse)) // no problems
Run Code Online (Sandbox Code Playgroud)

当我在您的实现中运行该示例时,导致java.lang.StackOverflowError了预期的结果。