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

[Scala] Pattern Matching(模式匹配)的更多相关文章

  1. scala pattern matching

    scala语言的一大重要特性之一就是模式匹配.在我看来,这个怎么看都很像java语言中的switch语句,但是,这个仅仅只是像(因为有case关键字),他们毕竟是不同的东西,switch在java中, ...

  2. learning scala pattern matching 02

    code package com.aura.scala.day01 object patternMatching02 { def main(args: Array[String]): Unit = { ...

  3. learning scala pattern matching

    code: package com.aura.scala.day01 import scala.util.Random object patternMatching01 { def main(args ...

  4. learning scala pattern matching 03

    code: package com.aura.scala.day01 object patternMatching03 { //当不同类型对象需要调用不同方法时,仅匹配类型的模式非常有用. def g ...

  5. Beginning Scala study note(5) Pattern Matching

    The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters ...

  6. C#9.0 终于来了,带你一起解读Pattern matching 和 nint 两大新特性玩法

    一:背景 1. 讲故事 上一篇跟大家聊到了Target-typed new 和 Lambda discard parameters,看博客园和公号里的阅读量都达到了新高,甚是欣慰,不管大家对新特性是多 ...

  7. Symbols of String Pattern Matching

    Symbols of String Pattern Matching in Introduction to Algorithms. As it's important to be clear when ...

  8. Zhu-Takaoka Two-dimensional Pattern Matching

    Two dimensional pattern matching. Details may be added later.... Corresponding more work can be foun ...

  9. 第74讲:从Spark源码的角度思考Scala中的模式匹配

    今天跟随王老师学习了从源码角度去分析scala中的模式匹配的功能.让我们看看源码中的这一段模式匹配: 从代码中我们可以看到,case RegisterWorker(id,workerHost,.... ...

随机推荐

  1. asp.net 中input radio checked 无效

    把Jq代码中的$(...).attr("checked",true) 换成$(...).prop("checked",true) ,

  2. C# 筛选string 类型里面的汉字,获取首字母字母,正则表达式Regex 常用验证

    界面效果 1.提取汉字 private void buttonX1_Click(object sender, EventArgs e) { if (TxtYuan.Text.Trim() != &qu ...

  3. 将以太坊封装为 ERC20

    将以太坊封装为 ERC20 TOKEN 很多 DAPP 都是在处理 ERC20接口的 token, 其实很容易将以太坊封装为 ERC20,这样就可以统一处理, 至少我目前在做的雷电网络就是这么处理的. ...

  4. webrowser卡死解决方案

    webrowser 是由于有道词典造成 解决方案,关闭有道或卸载:

  5. strcmp返回值布尔类型的判断

    strcmp: 用于比较两个字符串,原型如下: int strcmp ( char const *s1, char const *s2):如果s1小于s2,strcmp函数返回一个小于零的值.如果s1 ...

  6. C# WPF Webbrowser 强制所有网页链接在同一页面打开

    只要搞懂Winform的  WPF稍微改一改就可以了 主类:负责跳转的 using System; using System.Collections.Generic; using System.Com ...

  7. Struts2学习第3天--OGNL、EL、值栈

    JAVA中的OGNL: 1 调用对象的方法: 2 访问对象的静态方法: 3 获取OGNLContext.Root中的数据. User: 4 访问Context: 关键还是在Struts2环境中的使用: ...

  8. NSRect 位置和尺寸

    前言 结构体 这个结构体用来表示事物的坐标点和宽高度. typedef CGRect NSRect; struct CGRect { CGPoint origin; CGSize size; }; t ...

  9. audio音频

    html5的audio功能上已经非常强大,回放,跳转,缓冲等以前只能用flash才能实现的功能,html5的audio都能轻松搞定 最近的一个项目使用到了这个功能,把我使用的情况写下来,供大家参考, ...

  10. 洛谷P4493 [HAOI2018]字串覆盖(后缀自动机+线段树+倍增)

    题面 传送门 题解 字符串就硬是要和数据结构结合在一起么--\(loj\)上\(rk1\)好像码了\(10k\)的样子-- 我们设\(L=r-l+1\) 首先可以发现对于\(T\)串一定是从左到右,能 ...