Scala中的match, 比起以往使用的switch-case有著更強大的功能,

1. 傳統方法

def toYesOrNo(choice: Int): String = choice match {
case 1 => "yes"
case 0 => "no"
case _ => "error"
} // toYesOrNo(1)=>"yes"
// toYesOrNo(0)=>"no"
// toYesOrNo(33)=>"error"
 

佔位符“_”表示預設的情形, 若不想使用"_"也可以寫成以下的形式,

def toYesOrNo(choice: Int): String = choice match {
case 1 => "yes"
case 0 => "no"
case whaterver => "whaterver "
}
 
2. 類型模式
 
可以使用保留字match來判斷類型
def f(x: Any): String = x match {
case i:Int => "integer: " + i
case _:Double => "a double"
case s:String => "I want to say " + s
} // f(1) → “integer: 1″Typ
// f(1.0) → “a double”
// f(“hello”) → “I want to say hello”

3. Functional approach to pattern matching

以下是一個Factorial的傳統遞迴方法

def fact(n: Int): Int =
if (n == 0) 1
else n * fact(n - 1)

改以pattern matching來實現, 又會如何呢??

def fact(n: Int): Int = n match {
case 0 => 1
case n => n * fact(n - 1)
}

4. 模式匹配與集合

來試試一個集合加總的遞迴實現, 我們可能會寫出以下的代碼

def length[A](list : List[A]) : Int = {
if (list.isEmpty) 0
else 1 + length(list.tail)
}

看起來沒什麼問題, 但在pattern matching下有更酷的寫法,

def length[A](list : List[A]) : Int = list match {
case _ :: tail => 1 + length(tail)
case Nil => 0
}

"Nil"代表集合為空時,

"_::tailX" 應該被理解成, “a list with whatever head followed by a tail.”我的解釋是能將一個list拆分為list.head與list.tail

接著我們可以來看看多個參數的pattern matching要怎麼做呢??

def parseArgument(arg : String, value: Any) = (arg, value) match {
case ("-l", lang) => setLanguageTo(lang)
case ("-o" | "--optim", n : Int) if ((0 < n) && (n <= 5)) => setOptimizationLevelTo(n)
case ("-o" | "--optim", badLevel) => badOptimizationLevel(badLevel)
case ("-h" | "--help", null) => displayHelp()
case bad => badArgument(bad)
}

在pattern中還有最重要的case class, 下一篇繼續介紹....

參考資料:

Playing with Scala’s pattern matching

A Tour of Scala: Case Classes

最新文章

  1. PHP 查看安装信息
  2. MS SQL数据类型比较
  3. zynq学习01 新建一个Helloworld工程
  4. vc6.0快捷键大全
  5. C#----使用WindowsMediaPlayer 同时播放多个声音
  6. .NET调用window串口读取电子秤的数据
  7. [AngularJS] Best Practise - Controller
  8. ubuntu的syslog为空,停止写入解决方法
  9. [Leetcode] Binary search, Divide and conquer--240. Search a 2D Matrix II
  10. java----dom4j 解析XML
  11. mysql5.7设置简单密码报错ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
  12. HDU2586How far away? LCA
  13. tensorflow nan
  14. 在 PHP 中使用 `yield` 来做内存优化
  15. ajax返回json时,js获取类型,是字符串类型
  16. 分布式文件系统FastDFS架构剖析
  17. poj2528 Mayor's posters【线段树】
  18. 将Excel导入DataGridView 中的&quot;select * from [Sheet1$]&quot;中[ ]里面表单名的动态获取
  19. Apache POI导出excel
  20. 微信公众号支付安卓和WP支付成功,苹果不能支付!

热门文章

  1. SharePoint Server 2013 Excel Web Access无法显示
  2. 51nod1258 序列求和 V4(伯努利数+多项式求逆)
  3. node创建一个简单的web服务
  4. SDUT OJ 顺序表应用3:元素位置互换之移位算法
  5. 前端CSS的基本素养
  6. 3.1、Factorization Machine模型
  7. 【算法笔记】B1018 锤子剪刀布
  8. poj 1964 City Game
  9. 危险系数(枚举点+bfs)--------蓝桥备战系列
  10. XMAL基础