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. React学习笔记3

    React的生命周期   生命周期分为三个阶段   1.mounted(初始化的时候) 当我们看见页面元素从JSX变成了DOM节点时,React组件已经被载入(mounted)到页面中了   2.up ...

  2. 解决"要执行请求的操作,WordPress需要访问您网页服务器的权限"

    比如我们在VPS主机中创建WordPress站点的时候,会有需要在线安装主题.插件等,但是点击下载安装的时候会有"要执行请求的操作,WordPress需要访问您网页服务器的权限. 请输入您的 ...

  3. Linux 内核list_head 学习

    Linux 内核list_head 学习(一) http://www.cnblogs.com/zhuyp1015/archive/2012/06/02/2532240.html 在Linux内核中,提 ...

  4. Ubuntu chmod 命令可以用来修改文件或文件夹的读写权限

    chmod 命令有两种使用方式 —————————————————————————— (1)chmod [ u / g / o / a ] [ + / - / = ] [ r / w / x ] fi ...

  5. Redis在window下安装以及配置

    一.安装Redis 1.Redis官网下载地址:http://redis.io/download,下载相应版本的Redis,在运行中输入cmd,然后把目录指向解压的Redis目录. 2.启动服务命令 ...

  6. 738. Monotone Increasing Digits

    Given a non-negative integer N, find the largest number that is less than or equal to N with monoton ...

  7. 搭建jumpserver堡垒机

    环境 系统: CentOS 7 IP: 192.168.244.144 关闭 selinux 和防火墙 # CentOS 7 $ setenforce 0  # 可以设置配置文件永久关闭 $ syst ...

  8. 【bzoj4987】Tree 树形dp

    Description 从前有棵树. 找出K个点A1,A2,-,Ak. 使得∑dis(AiAi+1),(1<=i<=K-1)最小. Input 第一行两个正整数n,k,表示数的顶点数和需要 ...

  9. pip_install的安装

    1.下载get-pip.py https://pip.pypa.io/en/latest/installing/#id9 2.运行 python get-pip.py 3.python -m pip ...

  10. 18、OpenCV Python 简单实现一个图片生成(类似抖音生成字母人像)

    __author__ = "WSX" import cv2 as cv import numpy as np def local_threshold(img): #局部阈值 gra ...