[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

A Tour of Scala: Case
Classes

时间: 2024-08-27 18:54:49

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

scala pattern matching

scala语言的一大重要特性之一就是模式匹配.在我看来,这个怎么看都很像java语言中的switch语句,但是,这个仅仅只是像(因为有case关键字),他们毕竟是不同的东西,switch在java中,只能是用在函数体类的,且需要结合break使用.但是,在scala语言中,pattern matching除了有case关键字,其他,似乎和java又有很多甚至完全不同的东西. scala在消息处理中为模式匹配提供了强大的支持! 下面看看模式匹配的英文定义: A pattern match incl

learning scala pattern matching 03

code: package com.aura.scala.day01 object patternMatching03 { //当不同类型对象需要调用不同方法时,仅匹配类型的模式非常有用. def goIDLE(device : Device) = device match { case p: Phone => p.screenOff case c:Computer => c.screenSaverOn } } abstract class Device case class Phone(mo

Programming in Scala (Second Edition) 读书笔记15 case class and pattern matching

一个算术表达式包含: 数字,变量,二元操作符,一元操作符.用下面几个类来模拟它们 package chapter15 abstract class Expr case class Var(name: String) extends Expr case class Number(num: Double) extends Expr case class UnOp(operator: String, arg: Expr) extends Expr case class BinOp(operator: 

Scala Learning(1): 使用Pattern Matching表达JSON

这是一个挺能展现Scala编程方式的例子,对正在熟悉Scala这门语言的开发者很有帮助. Representing JSON 用Scala来表达JSON(Java Script Object Notation)结构, { "firstname" : "John", "lastname" : "Smith", "address" : { "street" : "21 2nd St

Beginning Scala study note(5) Pattern Matching

The basic functional cornerstones of Scala: immutable data types, passing of functions as parameters and pattern matching. 1. Basic Pattern Matching In Scala, your cases can include types, wildcards, sequences, regular expressions, and so forth. scal

Scala 函数式程序设计原理(4)--Types and Pattern Matching

4.1 Objects Everywhere Pure Object Orientation: A pure object-oriented language is one in which every value is an object. If the language is based on classes, this means that the type of each value is a class. 4.2 Functions as Objects (x: Int) => x *

Postgresql - Pattern Matching

There are three separate approaches to pattern matching provided by PostgreSQL: the traditional SQL LIKE operator, the more recent SIMILAR TO operator (added in SQL:1999), and POSIX-style regular expressions. Aside from the basic "does this string ma

Spark源码的角度思考Scala中的模式匹配

学习了从Spark源码的角度思考Scala中的模式匹配,如case class应用,伴生对象中用apply,所以没有new class,直接进行模式匹配,例子如下 Case class RegisterWorker( Id: string, Host: string, Port: int, Cores:int, Memory:int, webUiPort:int, publicAddress:string, Extend DeployMessage{ Utils.checkHost(host,”

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

今天跟随王老师学习了从源码角度去分析scala中的模式匹配的功能.让我们看看源码中的这一段模式匹配: 从代码中我们可以看到,case RegisterWorker(id,workerHost,........){}这里为模式匹配,而我们的模式匹配类RegisterWorker之前就已定义好,如下图: 我们可以看到,我们的模式匹配类是已经定义好的,当我们的master接收到worker发来的消息时,进行模式匹配: . 这里还有一个知识点,我们可以发现,当我们进行模式匹配时,我们并没有使用new方法