当前位置:网站首页>Scala higher order (IX): pattern matching in Scala
Scala higher order (IX): pattern matching in Scala
2022-07-29 07:22:00 【Think hard, Xiao Zhao】
Hello everyone , I can't think of Xiao Zhao .
Creation time :2022 year 7 month 21 Japan
Blog home page : Click here to enter the blog home page
—— Migrant workers in the new era
—— Look at the world with another kind of thinking logic
Today is to join CSDN Of the 1236 God . I think it's helpful and troublesome. I like it 、 Comment on 、️ Collection
List of articles
The main share Scala About pattern matching in ,Scala Pattern matching in is similar to Java Medium switch grammar , however Scala Based on Java The special function is added to the thought of .
One 、 summary
Basic grammar
value match {
case caseVal1 => returnVal1
case caseVal2 => returnVal2
...
case _ => defaultVal
}
In pattern matching Syntax , use match Keyword declaration , Each branch uses case Keyword to declare , When needed
When you want to match , From the first case Branch start , If the match is successful , Then execute the corresponding logic code , If horse
Configuration failed , Continue to the next branch for judgment . If all case None of them match , Then it will execute case _ Branch , Be similar to Java in default sentence .
for instance :
val x: Int = 2
val y: String = x match {
case 1 => "one"
case 2 => "two"
case 3 => "three"
case _ => "other"
}
Second example :
// Example : Use pattern matching to realize simple binary operation
val a = 25
val b = 21
def matchOualop(op: Char) = op match {
case '+' => a + b
case '-' => a - b
case '*' => a * b
case '/' => a / b
case _ => " Illegal operation "
}
println(matchOualop('+'))
println(matchOualop('-'))
println(matchOualop('\\'))
- If all
caseNone of them match , Then it will executecase _Branch , Be similar to Java in default sentence , If there is nocase _Branch , Then it will throwMatchError. - Every
casein , No need to usebreaksentence , Automatic interruptcase. match caseThe statement can match any type , Not just literal .=>The following code block , Until the nextcaseThe code before the statement is executed as a whole , have access to{}Cover up , You can also exclude .
Two 、 Mode guard
When it is necessary to match the data content of a certain range , You can operate pattern guard in pattern matching , Be similar to for Loop guard in push down .
for instance :
object Test01_PatternMatchBase {
def main(args: Array[String]): Unit = {
// Mode guard
// Find the absolute value of an integer
def abs(num: Int) = num match {
case i if i >= 0 => i
case i if i < 0 => -i
}
println(abs(11))
println(abs(-11))
}
}
3、 ... and 、 Pattern matching type
Scala in , Pattern matching can match all literal quantities , Including strings , character , Numbers , Boolean and so on .
Constant
// Match constants
def describeConst(s: Any): String = s match {
case 1 => "number 1"
case "hello" => "String hello"
case '+' => "+"
case 's' => "Char s"
case _ => ""
}
println(describeConst(1))
println(describeConst('s'))
println(describeConst(11))
type
// Match type
def deprecateType(x: Any): String = x match {
case i: Int => "int" + i
case s: String => "String" + s
case list: List[String] => "list" + list
case array: Array[Int] => "Array[Int]" + array.mkString("-")
case a => "Something type"
}
println(deprecateType(23))
println(deprecateType("12"))
println(deprecateType(List("mi", "hao")))
println(deprecateType(List(12, 21)))
Array
You can define multiple matching forms for arrays , Fuzzy element type matching can be defined 、 The number of elements matches or the exact value of an array element matches
// The match array
for (arr <- List(
Array(0),
Array(1, 0),
Array(0, 1, 0),
Array(1, 1, 0),
Array(12, 21, 34, 32),
Array("hello", 34, 32),
)) {
val result = arr match {
case Array(0) => "0"
case Array(1, 0) => "Array(1,0)"
case Array(x, y) => "Array:" + x + ", " + y
case Array(0, _*) => " With 0 The first array "
case Array(x, 1, y) => " In the middle 1 Ternary array of "
case _ => "something else"
}
}
list
Use :: Operator matching first :: second :: rest, Break a list into three , A list of the first, second, and remaining elements .
// Match list Mode one
for (list <- List(
List(0),
List(1, 0),
List(0, 0, 0),
List(1, 1, 0),
List(999)
)) {
val result = list match {
case List(0) => "0"
case List(x, y) => "list:" + x + ", " + y
case List(0, _*) => " With 0 At the beginning list"
case List(a) => "list(a)" + a
case _ => "something else"
}
}
// Mode two
val list = List(1, 34, 3, 2, 3, 2, 3, 6)
list match {
case first :: second :: rest => println(s"first:$first second: $second rest: $rest")
case _ => "something else"
}
Tuples
Can match n Tuples 、 Match element type 、 Match element values . If you only care about a certain element , Others can use wildcards or variables . Tuple size is fixed , So it can't be used _*.
// A tuple type
for (tuple <- List(
(0, 1),
(0, 1),
(0, 1, 0),
(0, 1, 1),
("hello", true, 0.5)
)) {
val result = tuple match {
case (a,b) => " "+ a + ", " +b
case (0,_) => "(0,_)"
case (a,1,_) => "(a,1,_)" + a
case (x,y,z) => "(x,y,z)"
case _ => "something else"
}
}
Object and sample class
A match object
object Test04_MathObject {
def main(args: Array[String]): Unit = {
val student = new Student("alice", 15)
// Match instances of objects
val result = student match {
case Student("alice", 15) => "alice, 15"
case _ => "else"
}
}
}
class Student(val name: String, val age: Int)
object Student {
def apply(name: String, age: Int): Student = new Student(name, age)
// Realization unapply
def unapply(student: Student): Option[(String, Int)] = {
if (student == null){
None
} else{
Some(student.name,student.age)
}
}
}
- When will
Student("alice", 15))Written incaseLater timecase Student("alice", 15) => "alice, 20", Will call... By defaultunapplyMethod ( Object extractor ),studentAsunapply
Method parameters ,unapplyMethods willstudentObject'snameandageAttribute extraction , AndStudent("alice", 15))Match the attribute values in caseObjects in theunapplyMethod ( Extractor ) returnSome, And all attributes are consistent , It's a successful match ,
Attribute inconsistency , Or returnNone, The match fails .- If only one attribute of the object is extracted , Then the extractor is
unapply(obj:Obj):Option[T] - If you extract multiple attributes of an object , Then the extractor is
unapply(obj:Obj):Option[(T1,T2,T3…)] - If the variable attributes of the object are extracted , Then the extractor is
unapplySeq(obj:Obj):Option[Seq[T]]
Sample class
case class Class name ( Parameters 1, Parameters 2,......)
- The sample class is still class , Compared with ordinary classes , But it automatically generates companion objects , And some common methods are automatically provided in the associated objects , Such as
apply、unapply、toString、equals、hashCodeandcopy. - Sample classes are classes optimized for pattern matching , Because it provides... By default
unapplyMethod , therefore , The sample class can use pattern matching directly , You don't have to do it yourselfunapplyMethod . - Every parameter in the constructor becomes
valDecorated variable
object Test_MatchCaseClass {
def main(args: Array[String]): Unit = {
val student = Student("alice", 15)
val result = student1 match {
case Student("alice", 15) => "alice, 20"
case _ => "else"
}
println(result)
}
}
case class Student(name: String, age: Int)
Four 、 Declare pattern matching in variables
Variable declaration can also be a pattern matching process .
object Test_MathTupleExtend {
def main(args: Array[String]): Unit = {
// 1. Match... When declaring variables
val (x,y) = (10,"hello")
println(s"$x $y")
val List(first,second,_*) = List(12,21,21,21,34)
println(s"$first $second ")
val fir :: sec :: res =List(12,21,34)
println(s"$fir $sec $res")
}
}
5、 ... and 、for Expression pattern matching
- When taking elements from tuples , Must use _1 _2 …, You can assign elements to variables with tuple assignment
- Specify the value of a specific element , It can realize functions similar to circular guard
object TestMatchFor {
def main(args: Array[String]): Unit = {
val map = Map("A" -> 1, "B" -> 0, "C" -> 3)
// // Direct will map Medium k-v Go through it
for ((k, v) <- map) {
println(k + " -> " + v) //3 individual
}
// Traverse value=0 Of k-v , If v No 0, Filter
for ((k, 0) <- map) {
println(k + " --> " + 0) // B->0
}
//if v == 0 Is a filter condition
for ((k, v) <- map if v >= 1) {
println(k + " ---> " + v) // A->1 and c->33
}
}
}
6、 ... and 、 Partial function pattern matching
- Partial function is also a kind of function , Through the partial function, we can easily check the input parameters more accurately . For example, the input type of the partial function is
List[Int],、 What is needed is that the first element is 0 Set , This is achieved through pattern matching .
Partial function definition
val second: PartialFunction[List[Int], Option[Int]] = {
case x :: y :: _ => Some(y)
}
second: Partial function namePartialFunction[List[Int], Option[Int]]: Partial function type- The function of this partial function is to return the input List The second element of the set
for instance :
object Test_PartialFunction {
def main(args: Array[String]): Unit = {
val list = List(("a,", 12), ("b", 34), ("c", 45))
// map transformation key unchanged value twice as much
val newList = list.map(tuple => (tuple._1, tuple._2 * 2))
// Pattern matching Assign values to elements
val newList2 = list.map(
tuple => {
tuple match {
case (word, count) => (word, count * 2)
}
}
)
// Omit lambda expression Representing partial function
val newList3 = list.map {
case (word, count) => (word, count * 2)
}
// Function application Find the absolute value
val positiveAbs: PartialFunction[Int, Int] = {
case x if x >= 0 => x
}
val pnegativeAbs: PartialFunction[Int, Int] = {
case x if x < 0 => -x
}
def abs(x: Int): Int= (positiveAbs orElse pnegativeAbs)(x)
println(abs(21))
}
}
This time Scala That's the end of the pattern matching section in , The knowledge point is relatively simple, but it is particularly flexible to use , I hope that's helpful !!!
边栏推荐
- Cvpr2021 | multi view stereo matching based on self supervised learning (cvpr2021)
- 一篇长文---深入理解synchronized
- Student achievement ranking system based on C language design
- WPF simple login page completion case
- dba
- [OpenGL] use of shaders
- Scala 高阶(十):Scala中的异常处理
- 时钟树综合(一)
- Vagrant box cluster processing
- Homebrew brew update doesn't respond for a long time (or stuck in updating homebrew...)
猜你喜欢

JS break and continue and return keywords

彻底搞懂kubernetes调度框架与插件

女研究生做“思维导图”与男友吵架!网友:吵架届的“内卷之王”....

Cvpr2021 | multi view stereo matching based on self supervised learning (cvpr2021)

js中break与continue和return关键字

作业7.28 文件IO与标准IO

SpingBoot整合Quartz框架实现动态定时任务(支持实时增删改查任务)
![Explanation of suffix automata (SAM) + Luogu p3804 [template] suffix automata (SAM)](/img/8b/f68503e09f218c26e34453b1b7fcd5.png)
Explanation of suffix automata (SAM) + Luogu p3804 [template] suffix automata (SAM)

使用VsCode配置MySQL实现连接、查询、等功能

Ethernet interface introduction
随机推荐
MySQL uses the client and select methods to view the summary of blob type fields
Win11vmware turns on the virtual machine and restarts on the blue screen and the solution that cannot be started
WPF嵌套布局案例
ETL为什么经常变成ELT甚至LET?
vagrant box 集群 处理
反射reflect
Leetcode 879. profit plan
Vscode remote debugging PHP solution through remotessh and Xdebug
MySQL----多表查询
Gin template
After three years of outsourcing, the salary of automatic testing after job hopping is twice that of the original. The secret is
Use vscode to configure Mysql to realize connection, query, and other functions
5-整合swagger2
MySQL - multi table query
Nodejs installation tutorial
最新百亿量化私募名单
作业7.28 文件IO与标准IO
Vagrant box cluster processing
leetcode力扣经典问题——4.寻找两个正序数组的中位数
gin 参数验证