# 泛函编程（2）－初次体验泛函编程

泛函编程和数学方程式解题相似；用某种方式找出问题的答案。泛函编程通用的方式包括了模式匹配（pattern matching）以及递归思维（Recursive thinking）。我们先体验一下：（在阅读本系列博客文章之前，相信读者已经对Scala语言及REPL用法有所了解了。在这就不去解释Scala的语法语意了。）

1 def reportError(msgId: Int): String = msgId match {

2 | case 1 => "Error number 1."

3 | case 2 => "Error number 2."

4 | case 3 => "Error number 3."

5 | case _ => "Unknown error!"

6 | }

7 reportError: (msgId: Int)String

1 reportError(2)

2 res3: String = Error number 2.

3

4 scala> reportError(-1)

5 res4: String = Unknown error!

1 def factorial(n: Int): Int = {

2 if ( n == 1) n

3 else n * factorial(n-1)

4 } //> factorial: (n: Int)Int

5 factorial(4) //> res48: Int = 24

1 def factorial_1(n: Int): Int = n match {

2 case 1 => 1

3 case k => k * factorial(n-1)

4 } //> factorial_1: (n: Int)Int

5 factorial_1(4) //> res49: Int = 24

1 factorial(4)

2 4 * factorial(3)

3 4 * (3 * factorial(2))

4 4 * (3 * (2 * factorial(1)))

5 4 * (3 * (2 * 1)) = 24

1 def factorial_2(n: Int): Int = {

2 var k: Int = n

3 var acc: Int = 1

4 while (k > 1) { acc = acc * k; k = k -1}

5 acc

6 } //> factorial_2: (n: Int)Int

7 factorial_2(4) //> res50: Int = 24

1 def factorial_3(n: Int): Int = {

2 @annotation.tailrec

3 def go(n: Int, acc: Int): Int = n match {

4 case 1 => acc

5 case k => go(n-1,acc * k)

6 }

7 go(n,1)

8 } //> factorial_3: (n: Int)Int

9 factorial_3(4) //> res51: Int = 24