假设我使用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的节点更改为另一个节点。很容易找到这个节点,但我不知道如何改变它。有没有简单的方法呢?
答案 0 :(得分:3)
这是一个非常有趣的问题!正如其他人已经指出的那样,您必须将整个路径从root更改为要更改的节点。不可变地图非常相似,您可以学习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
}
}
}
答案 1 :(得分:2)
由于您的树结构是不可变的,您必须更改从节点到根的整个路径。 当您访问树时,保留受访节点的列表,然后使用复制方法as suggested by pr10001将所有节点更新到根目录。
答案 2 :(得分:1)
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))