0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## 泛函编程（3）－认识Scala和泛函编程

接着昨天的文章，再示范一个稍微复杂一点的尾递归tail recursion例子：计算第n个Fibonacci数。Fibonacci数第一、第二个数值分别是0,1，按顺序后面的数值是前面两个数的加合。例如：0,1,1,2,3,5...

`````` 1 def fib(n: Int): Int = {
2     @annotation.tailrec
3       def go(cnt: Int, prev: Int, cur: Int): Int = cnt match {
4         case m if (m < 0 ) => sys.error("Negative Number Not Allowed!")
5         case 0 => prev
6         case c => go(cnt-1,cur, prev + cur)
7       }
8       go(n,0,1)
9   }                                               //> fib: (n: Int)Int
10   fib(5)                                          //> res52: Int = 5``````

``````1 fib(5)
2   go(5,0,1)
3   go(4,1,0+1)                                         = go(4,1,1)
4   go(3,(0+1),1+(0+1))                                 = go(3,1,2)
5   go(2,1+(0+1),(0+1)+(1+(0+1)))                       = go(2,2,3)
6   go(1,(0+1)+(1+(0+1)),(1+(0+1))+(0+1)+(1+(0+1)))    = go(1,3,5)
7   go(0,5,8) => 5``````

Scala的函数（function）还是值得提的。函数可以当作标准的对象使用：可以当作另一个函数的输入参数或者结果值。接受函数作为输入参数或者返回另一函数作为结果的函数被称之为高阶函数（high order function）。在Scala编程里匿名函数（anonymous function or lamda function)或函数文本（function literal）的使用也很普遍。用书上的代码样例来示范：

``````1 def formatResult(name: String, n: Int, f: Int => Int) = {
2   val msg = "The %s of %d is %d."
3   msg.format(n, f(n))
4 }``````

``````1 def main(args: Array[String]): Unit = {
2   println(formatResult("absolute value", -42, abs))
3   println(formatResult("factorial", 7, factorial))
4   println(formatResult("increment", 7, (x: Int) => x + 1))
5   println(formatResult("increment2", 7, (x) => x + 1))
6   println(formatResult("increment3", 7, x => x + 1))
7   println(formatResult("increment4", 7, _ + 1))
8   println(formatResult("increment5", 7, x => { val r = x + 1; r }))
9 }``````

+ 关注