尾递归是递归的一种,尾递归是函数式编程的常见写法,特点在于会在函数的最末调用自身。

尾递归会在编译期优化,因此不用担心递归造成的栈溢出问题。

举例:

 1 val file = List("warn 2013 msg", "warn 2012 msg",
 2   "error 2013 msg", "warn 2013 msg")
 3 
 4 def wordcount(str: String): Int = str.split(" ").count("msg" == _)
 5 
 6 def foldLeft(list: List[Int])(init: Int)(f: (Int, Int) => Int): Int = {
 7   list match {
 8     case List() => init
 9     case head :: tail => foldLeft(tail)(f(init, head))(f)
10   }
11 }
12 
13 val num = foldLeft(file.map(wordcount))(0)(_ + _)
14 
15 println("wordcount:" + num)

其中:

当用List做match case时。可以使用 :: 来解构。返回第一个元素head和剩余元素tail,写成h::t,也行,只要解构就行。

List()表示这个是空列表。

这个_ + _,为什么可以这样省略,不太明白。

不省略的版本应该是(x: Int, y: Int)=> (x + y)