gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:49:00 25 4
gpt4 key购买 nike

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

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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com