# 泛函编程（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

210 篇文章59 人订阅

0 条评论

## 相关文章

931

### java.base.jmod

/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/jmods\$ jmod list java....

1182

### 2018年SCI期刊最新影响因子排行，最高244，人工智能TPAMI9.455

2018年6月26日，最新的SCI影响因子正式发布，涵盖1万2千篇期刊。CA-Cancer J Clin 依然拔得头筹，其影响因子今年再创新高，达244.585...

1482

### 高通Audio中ASOC的machine驱动

ASoC被分为Machine、Platform和Codec三大部分，其中的Machine驱动负责Platform和Codec之间的耦合以及部分和设备或板子特定的...

1K4

1953

### java.sql.SQLException: connection holder is null

java.sql.SQLException: connection holder is null

1481

### Knapsack problem algorithms for my real-life carry-on knapsack

I'm a nomad and live out of one carry-on bag. This means that the total weight o...

1192

2152

### Oracle sqlldr 如何导入一个日期列

1. LOAD DATA INFILE * INTO TABLE test FIELDS TERMINATED BY X'9' TRAILING NULLCO...

1876

### MongoDB系列五（地理空间索引与查询）.

Volvo Today, Volvo announced i...

2772