【问题标题】:Change node in Scala case class treeScala案例类树中的更改节点
【发布时间】:2012-02-03 13:52:35
【问题描述】:

假设我有一些使用案例类构建的树,类似这样:

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))

现在我想构建一个方法来将具有某个 id 的节点更改为另一个节点。很容易找到这个节点,但我不知道如何更改它。有什么简单的方法吗?

【问题讨论】:

  • 我假设 Branch 和 Leaf extends Tree,对吧?
  • 所讨论的数据结构不同,但这个问题与我链接的问题大致相同,并且该问题中的所有答案都是通用的并且适用于您的问题。
  • 是的,一般来说问题是关于同一件事,但@dave 为我的问题提供了更好(更简单)的答案。

标签: scala tree pattern-matching case-class


【解决方案1】:

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

我的建议是:

  • Tree 更改为Node。你甚至在你的问题中称它为节点,所以这可能是一个更好的名字。
  • value 拉到基类。再次,您在问题中谈到了这一点,所以这可能是适合它的地方。
  • 在您的替换方法中,请确保如果 Node 及其子项均未更改,请不要创建新的 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
    }
  }
}

【讨论】:

  • 感谢您的回复!我会将它用于更复杂的结构,所以它应该可以很好地工作。
【解决方案2】:

由于您的树结构是不可变的,因此您必须更改从节点到根的整个路径。 当你访问你的树时,保留一个访问过的节点列表,然后,使用复制方法 as suggested by pr10001 将所有节点更新到根节点。

【讨论】:

    【解决方案3】:

    copy 方法:

    val tree1 = Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(4), Leaf(5),6))
    val tree2 = tree1.copy(b2 = tree1.b2.copy(b1 = Leaf(5))
    // -> Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(5), Leaf(5),6))
    

    【讨论】:

    • 不缩放到任意深度。如果您有兴趣,请查看我标记为重复的问题。
    • 没错,但我没有意识到 OP 要求的是通用解决方案。 =)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多