scala binary tree, adding an element -


i trying change end nodes in binary tree. how make methods change_right_tree , change_left_tree?

the compiler complaining reassigning val. when change things var, covariant errors.

sealed abstract class tree[+t] { } case object end extends tree[nothing] {   override def tostring = "." }  case class node[+t](var question: string,  left: tree[t] = end, right: tree[t] = end) extends tree[t] {   override def tostring = "t(" + question.tostring + " " + left.tostring + " " + right.tostring + ")"    def set_question(str : string) = {question = str}    def get_answer(answer : boolean) = {     if (answer){       left     }else {       right     }   }   // unclear on need make work   def change_left_tree( new_tree : tree[t]) = {this.left = new_tree}   def change_right_tree( new_tree : tree[t]) = {this.right = new_tree} } 

solution: if remove '+' node class declaration code compile.

explanation:

when declare class covariant type [+t] can declare subclasses narrower type. tree class has declared covariant type allow declaring case object end.

but declaring class node covariant type [+t] incorrect when wanted mutable. understand better imagine moment compiler didn't stop , allowed compile following code (i removed other methods simplicity of example):

case class node[+t](var question: string, var left: tree[t] = end, var right: tree[t] = end)  extends tree[t] {     def change_left_tree( new_tree : tree[t]) = {this.left = new_tree}     def change_right_tree( new_tree : tree[t]) = {this.right = new_tree} } 

now can following:

val stringnode:node[string] = new node("string node") val intnode:node[int] = new node("int node") val anynode:node[any] = stringnode anynode.change_left_tree(intnode) 

and node[int] left node of node[string]. mixing covariance , mutability break type safety.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -