Scala 中的递归函数调用

Man*_*oid 1 recursion scala

我正在尝试编写一个递归求和函数:

val sumRecursive = (list: List[Int]) => list match {
  case Nil => 0
  case x::xs => x + sumRecursive(xs)
}
Run Code Online (Sandbox Code Playgroud)

它给出错误:

错误:(16, 23) 递归值 sumRecursive 需要类型 case x::xs => x + sumRecursive(xs)

我知道递归函数需要声明其返回类型。但我不确定如何在这个代码结构中做到这一点。

Xav*_*hot 5

由于它抱怨缺少显式类型,因此您可以像指定经典类型一样提供它 ( val a: Int = 5):

val sumRecursive: List[Int] => Int =
  list => list match {
    case Nil => 0
    case x::xs => x + sumRecursive(xs)
  }
Run Code Online (Sandbox Code Playgroud)

这使:

scala> sumRecursive(List(1, 2, 3))
res0: Int = 6
Run Code Online (Sandbox Code Playgroud)

为了进行类比val a: Int = 5

  • asumRecursive
  • IntList[Int] => Int
  • 5list => list match { case Nil => 0; case x::xs => x + sumRecursive(xs) }