在Scala案例类树中更改节点

the*_*res 5 tree scala pattern-matching case-class

假设我使用case类构建了一些树,类似于:

abstract class Tree
case class Branch(b1:Tree,b2:Tree, value:Int) extends Tree
case class Leaf(value:Int) extends Tree
var tree = Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(4), Leaf(5),6))
Run Code Online (Sandbox Code Playgroud)

现在我想构建一个方法来将具有一些id的节点更改为另一个节点.很容易找到这个节点,但我不知道如何改变它.有没有简单的方法呢?

lee*_*777 3

这是一个非常有趣的问题!正如其他人已经指出的那样,您必须更改从根到要更改的节点的整个路径。不可变映射非常相似,您可以通过查看 Clojure 的 PersistentHashMap学到一些东西。

我的建议是:

  • 改成。TreeNode您甚至在问题中将其称为“节点”,所以这可能是一个更好的名称。
  • 拉升value到基类。您在问题中再次谈到了这一点,所以这可能是正确的地方。
  • 在您的替换方法中,请确保如果 aNode及其子项均未更改,则不要创建新的Node.

注释在下面的代码中:

// Changed Tree to Node, b/c that seems more accurate
// Since Branch and Leaf both have value, pull that up to base class
sealed abstract class Node(val value: Int) {
  /** Replaces this node or its children according to the given function */
  def replace(fn: Node => Node): Node

  /** Helper to replace nodes that have a given value */
  def replace(value: Int, node: Node): Node =
    replace(n => if (n.value == value) node else n)
}

// putting value first makes class structure match tree structure
case class Branch(override val value: Int, left: Node, right: Node)
     extends Node(value) {
  def replace(fn: Node => Node): Node = {
    val newSelf = fn(this)

    if (this eq newSelf) {
      // this node's value didn't change, check the children
      val newLeft = left.replace(fn)
      val newRight = right.replace(fn)

      if ((left eq newLeft) && (right eq newRight)) {
        // neither this node nor children changed
        this
      } else {
        // change the children of this node
        copy(left = newLeft, right = newRight)
      }
    } else {
      // change this node
      newSelf
    }
  }
}
Run Code Online (Sandbox Code Playgroud)