假设我使用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 } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。