Convert sphere function to tail recursive function

asi*_*sif 1 scala tail-recursion

I have implemented Sphere function (takes a List of elements, squares every element and returns sum) in Scala. I want to convert this function to tail recursive. My code is here

def Sphere(list: List[Double]): Double = {
  val power = list.map(math.pow(_, 2))
  power.reduce(_+_)
}
Run Code Online (Sandbox Code Playgroud)

pme*_*pme 5

It looks like:

  @tailrec
  def Sphere(list: List[Double], result: Double = 0): Double = list match {
    case Nil => result
    case x::xs => Sphere(xs, result + math.pow(x, 2))
  }

  println(Sphere(List(1,3,4,5)))
Run Code Online (Sandbox Code Playgroud)

With @tailrec you make sure that it is actually tail recursive (the compile will fail).

Important is:

  • that the last call is to itself
  • that it has the intermediate result in the parameter list
  • x is the head of the List where you do the calculation
  • xs is the rest of the List (the tail) - where you append the recursive function on - until the List is empty > Nil.