Diogo Angra
Diogo Angra

Reputation: 15

What is the correct way to invoke this Scala method on main?

Me and my mates have to do a presentation on functional programming and we are trying to present standard deviation with FP, since they are beasts, they did the Scheme code for it. Meanwhile, I'm trying to convert that code into Scala since Sacla will be easier for introduction bcoz everyone in class is familiar with Java.

def soma(lista: List[Double]): Double={
 if(lista.isEmpty){
  return 0
 }else{
  return lista.head+soma(lista.tail)
 }
}

When I try to invoke it with soma(nameOfTheList), the program simply does nothing, it gives me no error message or output. I tried the main as follows:

    def main(args: Array[String]){
  val nums: List[Double] = List(1, 2, 3, 4)
  println(soma(nums))
}

The idea is to use lists heavily but not use anything ready-made other than car/cdr or head/tail.

Upvotes: 0

Views: 60

Answers (2)

Tim
Tim

Reputation: 27356

This is the code you want:

object TestApp extends App {
  def soma(lista: List[Double]): Double = {
    @annotation.tailrec
    def loop(list: List[Double], res: Double): Double =
      list match {
        case hd :: tail => loop(tail, res + hd)
        case _ => res
      }

    loop(lista, 0.0)
  }

  val nums: List[Double] = List(1, 2, 3, 4)

  println(soma(nums))
}

But I suggest learning a bit more Scala (and FP) before giving talks about it.

Upvotes: 2

Mahesh Chand
Mahesh Chand

Reputation: 3250

I have run the same method and it worked fine.

object Main {
  def main(args: Array[String]): Unit = {
    def soma(lista: List[Double]): Double={
      if(lista.isEmpty){
        return 0
      }else{
        return lista.head+soma(lista.tail)
      }
    }

    val nums: List[Double] = List(1, 2, 3, 4)
    println(soma(nums))
  }
}

Hope it will help.

Upvotes: 0

Related Questions