[Scala] Pattern Matching(模式匹配)
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
[Scala] Pattern Matching(模式匹配)的更多相关文章
- scala pattern matching
scala语言的一大重要特性之一就是模式匹配.在我看来,这个怎么看都很像java语言中的switch语句,但是,这个仅仅只是像(因为有case关键字),他们毕竟是不同的东西,switch在java中, ...
- learning scala pattern matching 02
code package com.aura.scala.day01 object patternMatching02 { def main(args: Array[String]): Unit = { ...
- learning scala pattern matching
code: package com.aura.scala.day01 import scala.util.Random object patternMatching01 { def main(args ...
- learning scala pattern matching 03
code: package com.aura.scala.day01 object patternMatching03 { //当不同类型对象需要调用不同方法时,仅匹配类型的模式非常有用. def g ...
- Beginning Scala study note(5) Pattern Matching
The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters ...
- C#9.0 终于来了,带你一起解读Pattern matching 和 nint 两大新特性玩法
一:背景 1. 讲故事 上一篇跟大家聊到了Target-typed new 和 Lambda discard parameters,看博客园和公号里的阅读量都达到了新高,甚是欣慰,不管大家对新特性是多 ...
- Symbols of String Pattern Matching
Symbols of String Pattern Matching in Introduction to Algorithms. As it's important to be clear when ...
- Zhu-Takaoka Two-dimensional Pattern Matching
Two dimensional pattern matching. Details may be added later.... Corresponding more work can be foun ...
- 第74讲:从Spark源码的角度思考Scala中的模式匹配
今天跟随王老师学习了从源码角度去分析scala中的模式匹配的功能.让我们看看源码中的这一段模式匹配: 从代码中我们可以看到,case RegisterWorker(id,workerHost,.... ...
随机推荐
- c#帮助类:发送邮件
private static string IsOpenSendMail = ConfigurationManager.AppSettings["IsOpenSendMail"]; ...
- SpringMVC+Hibernate 项目开发之三 (创建SpringMVC项目)
引用(很全面了):http://blog.csdn.net/dhx20022889/article/details/38041039 我只想说默认创建的项目使用的Spring版本可能不是你想要的,可以 ...
- RadASM的主题更换!
RadASM的代码编辑器默认背景色位黑色,我很不习惯,决定更换它,按照下面步骤,我把RadASM的代码编辑器默认背景色成功更换成了白色: 1, 2, 3, 4,
- 题解 P2863 【[USACO06JAN]牛的舞会The Cow Prom】
题目链接 赤裸裸的板子,就加一个特判就行.直接上代码 #include<stdio.h> #include<algorithm> #include<iostream> ...
- Error creating bean with name 'dateSource' defined in file 错误信息
问题的原因: 在web项目中搭建SSM框架,启动Tomcat时出现错误信息 有配置文件:applicationContext-mybatis.xml (Spring配置) spring-servlet ...
- 2008R2 无法安装 HDP Apache 系列服务解决方案
执行下面的 PS 就好了. 特别是 第三行在执行的时候选择 [A] Set-ExecutionPolicy "AllSigned" Enable-PSRemoting Set- ...
- C++_友元1-友元类是什么
友元函数:不是类的成员函数,但是能够访问类的私有数据成员. 之前有个矛盾就是规定非成员函数不能直接访问类的私有数据,但是这会儿却可以,但那只是针对常规非成员函数而言,特殊的非成员函数就可以访问类的私有 ...
- ABP中文网入门篇教程中的一个bug
入门--从空项目开始--使用ASP.NET Core Web Application https://cn.abp.io/documents/abp/latest/Autofac-Integratio ...
- 【KMP】洛谷P2375 [NOI2014]动物园 题解
一开始的方向应该对了,但是没有想到合理的优化还是没写出来…… 题目描述 近日,园长发现动物园中好吃懒做的动物越来越多了.例如企鹅,只会卖萌向游客要吃的.为了整治动物园的不良风气,让动物们凭自己 ...
- edX MITx: 6.00.1x Introduction to Computer Science and Programming Using Python 课程 Week 1: Python Basics Problem Set 1 Problem 3
Assume s is a string of lower case characters. Write a program that prints the longest substring of ...