在Scala案例类树中更改节点
发布时间:2020-12-16 18:18:09 所属栏目:安全 来源:网络整理
导读:假设我使用case类构建了一些树,类似于: abstract class Treecase class Branch(b1:Tree,b2:Tree,value:Int) extends Treecase class Leaf(value:Int) extends Treevar tree = Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(4),Leaf(5),6)) 现在我想构建一
|
假设我使用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
}
}
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
