Home > Back-end >  how can i get arround reassignement to val , binary search tree scala
how can i get arround reassignement to val , binary search tree scala

Time:05-19

i'm doing the method delete(k) for a binary search tree in scala i have a trait like this

trait BST { 
   def delete(k:Int) :BST
}
case object Empty extends BST {..}
case class Node(data: Int, left: BST, right: BST) extends BST {
  ...
  override def delete(k: Int) :BST = {
   def delete(Node : BST ,key:Int): BST ={
    Node match {
      case Empty => Node
      case Node(x, left, right)=> if(key<x) left=delete(left,key)
                                            ...
        }
     }
    ...
   }

this is where i am stuck , i already know the algorithm for the method , have done it in other langages but in scala , i can't seem to assign/change left and right trees , it says it's a reassignement to val , anyway to get arround this without changing the definition of my Binary search tree ?

CodePudding user response:

In Scala idiomatic approach is to try avoiding mutation, so you don't reassign left but create and return a new node (also move key < x condition to pattern guard):

def delete(Node : BST ,key:Int): BST ={
    Node match {
      case Empty => Node
      case Node(x, left, right) if key < x => Node(x, delete(left , key), right)
                                            ...
    }
}
  • Related