Is it possible to implement a bi-directional tree in a case class. This seems like it should be easy, but I'm getting stumped
case class Node(name:String, parent:Option[Node], children:List[Node])
I want to add a child (and get a new root) -- something like
def addChild(n:String):Node = {
Node(name, parent, Node(n, Some(this), Nil)::children)
}
But that won't work because the "parent" in the child will no longer refer to the Node which lists the child as a child. Is this possible with immutable lists and case classes?
Based on answer given below
case class Node(name: String, parent: () => Option[Node], children: List[Node]) {
def makeChild(name: String) = {
lazy val newParent:Node = Node(this.name, this.parent, kid :: this.children)
lazy val kid:Node = Node(name, () => Some(newParent), Nil)
newParent
}
}