scala - 更改 Scala 案例类树中的节点

标签 scala tree pattern-matching case-class

假设我使用案例类构建了一些树,如下所示:

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 的节点更改为另一个节点。这个节点很容易找到,但是不知道怎么改。有没有简单的方法可以做到这一点?

最佳答案

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

我的建议是:

  • 更改 TreeNode .你甚至在你的问题中称它为节点,所以这可能是一个更好的名字。
  • value直到基类。再一次,你在你的问题中谈到了这一点,所以这可能是正确的地方。
  • 在您的替换方法中,请确保如果不是 Node它的 child 也不会改变,不要创建一个新的 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
        }
      }
    }
    

    关于scala - 更改 Scala 案例类树中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9129671/

    相关文章:

    scala - 未能初始化编译器 : object java. lang.Object in compiler mirror not found

    scala.MatchError : <SomeStringvalue> (of class java. lang.String)

    php - PHP/MySQL 中的简单递归树

    haskell创建一棵不平衡树

    functional-programming - "square"元组的 Ocaml 模式匹配?

    scala - HBase - Scala - 无法初始化类 ProtobufUtil

    Scala - 如何将字符串值传递给数据框过滤器 (Spark-Shell)

    java - 如何遍历 N 叉树

    java - 应该在 java.util.Scanner 中使用什么模式来获取下一个字符串标识符?

    regex - 在 Expect 的正则表达式模式匹配中访问我的捕获组到变量