在Scala案例类树中更改节点

假设我使用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))

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

解决方法

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

我的建议是:

>将树更改为节点.你甚至在你的问题中称它为节点,所以这可能是一个更好的名字.
>将值拉至基类.再一次,你在你的问题中谈到这一点,所以这可能是适合它的地方.
>在替换方法中,请确保如果节点及其子节点都没有更改,请不要创建新节点.

评论在下面的代码中:

// 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
    }
  }
}

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...