Pattern Matching in Scala [Simple Pattern Matching, Match Type, Guard, Match Sample Tight, Match Set, Pattern Matching in Variable Declarations, Match for1 Expression]

Pattern match ing

There is a very powerful matching mechanism in Scala, such as:

  • Judging Fixed Values
  • Type Query
  • Quick data acquisition

Simple pattern matching

A pattern match contains a series of alternatives, each starting with the keyword case, and each alternative contains a pattern and one or more expressions. Arrow symbol=>separates the pattern from the expression.

Format:

variable match {
	case "Constant 1" => Expression 1
	case "Constant 2" => Expression 2
	case "Constant 3" => Expression 3
	case _ => Expression 4		//Default Match
}

Execution process:

  • 1. First execute the first case to see if the variable value is consistent with the constant value corresponding to that case.
  • 2. If consistent, the expression corresponding to the case is executed.
  • 3. If inconsistent, execute the next case backwards to see if the variable value is consistent with the constant value corresponding to the case.
  • 4. By analogy, if all cases do not match, execute case_ Corresponding expression.

Case Requirements:

  • 1. Prompt the user to enter a word and accept it.
  • 2. Determine if the word can match a word, and if it can match, return a sentence.
  • 3. Print the results.
WordReturn
hadoopLarge Data Distributed Storage and Computing Framework
zookeeperLarge Data Distributed Coordination Service Mining
sparkLarge Data Distributed Memory Computing Framework
Not MatchedNot Matched
import scala.io.StdIn

object Simple pattern matching {

  def main(args: Array[String]): Unit = {
    //1. Prompt the user to enter a string and accept it
    println("Please enter a string:")
    var str = StdIn.readLine()

    //2. Determine if the string is the specified content and accept the result
    val result = str match {
      case "hadoop" => "Large Data Distributed Storage and Computing Framework"
      case "zookeeper" => "Large Data Distributed Coordination Service Framework"
      case "spark" => "Large Data Distributed Memory Computing Framework"
      case _ => "Not Matched"
    }

    //3. Print results
    println(result)
    println("-" * 15) //Split Line

    //Short form
    str match {
      case "hadoop" => println("Large Data Distributed Storage and Computing Framework")
      case "zookeeper" => println("Large Data Distributed Coordination Service Framework")
      case "spark" => println("Large Data Distributed Memory Computing Framework")
      case _ => println("Not Matched")
    }
  }

}
Please enter a string:
spark
 Large Data Distributed Memory Computing Framework
---------------
Large Data Distributed Memory Computing Framework

Process finished with exit code 0

Match type

In addition to matching data, match expressions can also be type matched. You can also use a match expression if you want to perform different logic depending on the data type.

Format:

Object Name match { 
	case Variable Name 1: Type 1 => Expression 1 
	case Variable Name 2: Type 2 => Expression 2 
	case 	Variable Name 3: Type 3 => Expression 3 
	... 
	case _ => Expression 4 
}

Note: Underlines can be used instead of matching variables in case expressions.

Case Requirements:

  1. Define a variable as Any type and assign it hadoop, 1, and 1.0, respectively
  2. Define pattern matching and print the name of the type separately

Code demonstration:

object Match type {

  def main(args: Array[String]): Unit = {
    //1. Define a variable as Any type and assign it hadoop, 1, and 1.0, respectively
    val a:Any = 1.0
    //2. Define pattern matching and print the name of the type separately
    val result = a match {
      case x:String => s"${x} yes String Type data"
      case x:Double => s"${x} yes Double Type data"
      case x:Int => s"${x} yes Int Type data"
      case _ => "Not Matched"
    }
    //3. Print results
    println(result)

    //4. Optimized version, if the variable is not used during the case check, you can use _ Replace
    val result2 = a match {
      case _:String => "String"
      case _:Double => "Double"
      case _:Int => "Int"
      case _ => "Not Matched"
    }
    println(result2)
  }

}
1.0 yes Double Type data
Double

Process finished with exit code 0

guard

The so-called guard refers to adding if conditional judgment to the case statement to make our code more concise.

Format:

variable match { 
	case Variable Name if Condition 1 => Expression 1 
	case Variable Name if Condition 2 => Expression 2 
	case Variable Name if Condition 3 => Expression 3 
	... 
	case _ => Expression 4 
}

Case Requirements:

  1. Read in a number a from the console (using StdIn.readInt)
  2. If a >= 0 and a <= 3, print [0-3]
  3. If a >= 4 and a <= 8, print [4,8]
  4. Otherwise, the print does not match

Code demonstration:

import scala.io.StdIn

object guard {

  def main(args: Array[String]): Unit = {
    //1. Read in a number a from the console (using StdIn.readInt)
    println("Please enter a number:")
    var num = StdIn.readInt()
    //2. Pattern Matching
    num match {
      //2.1 If a >= 0 and a <= 3, print [0-3]
      case a if a >= 0 && a <= 3 => println("[0-3]")
      //2.2 If a >= 4 and a <= 8, print [4,8]
      case a if a >= 4 && a <= 8 => println("[4-8]")
      //2.3 Otherwise, the print does not match
      case _ => println("Not Matched")
    }
  }

}
Please enter a number:
4
[4-8]

Process finished with exit code 0

Match Sample Class

You can use pattern matching in Scala to match the sample class, which allows you to quickly get member data from the sample class.

Format:

Object Name match { 
	case Sample Type 1(Field 1, Field 2, field n) => Expression 1 
	case Sample Type 2(Field 1, Field 2, field n) => Expression 2 
	case Sample Type 3(Field 1, Field 2, field n) => Expression 3 
	... 
	case _ => Expression 4 
}

Be careful:

  1. In parentheses after the sample type, write the same number of fields as the sample class.
  2. When pattern matching is done through match, the object to be matched must be declared as Any type.

Case Requirements:

  1. Create two sample classes Customer (with name and age fields) and Order (with id fields)
  2. Define objects of two sample classes and specify Any type
  3. Use patterns to match these two objects and print their member variable values separately

Code demonstration:

object Match Sample Class {

  //1. Create two sample classes Customer, Order
  //1.1 Customer contains name, age fields
  case class Customer(var name: String, var age: Int)
  //1.2 Order contains id field
  case class Order(id: Int)

  def main(args: Array[String]): Unit = {
    //2. Define the objects of two case classes and specify the type of Any
    val c: Any = Customer("Sugar sugar", 73)
    val o: Any = Order(123)
    val arr: Any = Array(0, 1)

    //3. Use patterns to match these two objects and print their member variable values separately
    c match {
      case Customer(a, b) => println(s"Customer Objects of type, name${a}, age=${b}")
      case Order(c) => println(s"Order Type, id=${c}")
      case _ => println("Not Matched")
    }
  }

}
Customer Objects of type, name Sugar sugar, age=73

Process finished with exit code 0

Match Set

In addition to the above capabilities, pattern matching in Scala can also be used to match arrays, tuples, collections (lists, sets, maps), and so on.

1. Matching Array

Requirements:

  1. Modify the code definition in turn to the following three arrays

  2. Use pattern matching to match the above array.

    Array(1,x,y)//Starts with 1, and the next two elements are not fixed
    Array(0)//Matches only one element of 0
    Array(0,...)//can be any number, but starts with 0

Code demonstration:

object Match Array {

  def main(args: Array[String]): Unit = {
    //1. Define three arrays
    val arr1 = Array(1, 2, 3)
    val arr2 = Array(0)
    val arr3 = Array(1, 2, 3, 4, 5)
    //2. Find the specified array by pattern matching
    arr1 match {
      //Match: Length is 3, first element is 1, the last two elements don't matter
      case Array(1, x, y) => println(s"The matching length is 3, the first element is 1, and the last two elements are: ${x},${y}")
      //Match: Array with only one 0 element
      case Array(0) => println("Match: Array with only one 0 element")
      //Match: the first element is 1, followed by an arbitrary array of elements
      case Array(1, _*) => println("Match: the first element is 1, followed by an arbitrary array of elements")
      //Other Checks
      case _ => println("Not Matched")
    }
  }

}
The matching length is 3, the first element is 1, and the last two elements are 2, 3

Process finished with exit code 0

2. Match List

  1. Modify the code definition in turn to the following three lists

  2. Use pattern matching to match the list above

    List(0)//Save only a list of 0 elements
    List(0,...)//List starting with 0, variable number
    List(x,y)//List with only two elements

Code demonstration:

object Match List {

  def main(args: Array[String]): Unit = {
    //1. Definition list
    var list1 = List(0)
    var list2 = List(0, 1, 2, 3, 4, 5)
    var list3 = List(1, 2)

    //2. Pattern matching by matching
    //Idea one: through List()
    list1 match {
      case List(0) => println("Match: List with only 0 elements")
      case List(0, _*) => println("Match: 0 at the beginning, followed by a casual list of elements")
      case List(x, y) => println(s"Match: A list of only two elements: ${x}, ${y}")
      case _ => println("Not Matched")
    }

    //Idea two: Using keywords to optimize Nil, tail
    list2 match {
      case 0 :: Nil => println("Match: List with only 0 elements")
      case 0 :: tail => println("Match: 0 at the beginning, followed by a casual list of elements")
      case x :: y :: Nil => println(s"Match: A list of only two elements: ${x}, ${y}")
      case _ => println("Not Matched")
    }
  }

}
Match: List with only 0 elements
 Match: 0 at the beginning, followed by a casual list of elements

Process finished with exit code 0

3. Matching tuples

Requirements:

  1. Modify the code in turn to define the following two tuples
  2. Match the tuples above using pattern matching

(1, x, y) //A tuple of three elements starting with one
(x, y, 5)//A tuple of three elements, the last element being 5

Reference code:

object Matching tuples {
  def main(args: Array[String]): Unit = {
    //1. Define two tuples
    val a = (1, 2, 3)
    val b = (3, 4, 5)
    val c = (3, 4)

    //2. Match specified elements by pattern matching
    a match {
      case (1, x, y) => println(s"Match: 3 in length, starting with 1, the last two elements are indifferent tuples, where the last two elements are: ${x},${y}")
      case (x, y, 5) => println(s"Match: Length is 3 and ends with 5. The first two elements are indifferent tuples, where the first two elements are: ${x},${y}")
      case _ => println("Not Matched")
    }
  }
}
Match: 3 in length, starting with 1, the last two elements are indifferent tuples, where the last two elements are: 2, 3

Process finished with exit code 0

Pattern Matching in Variable Declarations

When defining variables, you can use pattern matching to get data quickly. For example, get data quickly from arrays, lists.

Case Requirements:

  1. Generate an array of 0-10 numbers, using pattern matching to get the second, third, and fourth elements, respectively
  2. Generate a list of 0-10 numbers, using pattern matching to get the first and second elements, respectively

Reference Code

object Pattern Matching in Variable Declarations {

  def main(args: Array[String]): Unit = {
    //1. Generate an array of 0-10 numbers and use pattern matching to get the second, third, and fourth elements, respectively
    //1.1 Generate an array containing 0-10 numbers
    val arr = (0 to 10).toArray
    //1.2 Use pattern matching to get the second, third, and fourth element, respectively
    val Array(_, x, y, z, _*) = arr
    //1.3 Print results
    println(x, y, z)
    println("-" * 15)

    //2. Generate a list of 0-10 numbers, using pattern matching to get the first and second element, respectively
    //2.1 Generate a list of 0-10 numbers
    val list = (0 to 10).toList
    //2.2 Use pattern matching to get the first and second element, respectively
    //Idea one:, List() implementation
    val List(a, b, _*) = list
    //Idea two: tail implementation
    val c :: d :: tail = list
    //2.3 Print results
    println(a, b)
    println(c, d)
  }

}
(1,2,3)
---------------
(0,1)
(0,1)

Process finished with exit code 0

Match for expression

Schema matching can also be used in Scala to match for expressions, enabling quick access to specified data and making our code look simpler and more elegant.

Case Requirements:

  1. Define variables to record the name and age of students, such as "Zhang San" -> 23, "Li Si" -> 24, "Wang Wu" -> 23, "Zhao Liu" -> 26
  2. Get information about all 23-year-old students and print the results

Reference code:

object matching for Expression {

  def main(args: Array[String]): Unit = {
    //1. Define variables to record the student's name and age
    val map1 = Map("Zhang San" -> 23, "Li Si" -> 24, "King Five" -> 23, "Zhao Six" -> 26)
    //2. Get information about all 23-year-old students
    //2.1 Format 1: Implemented by if statement
    for((k, v) <- map1 if v == 23) println(s"${k} = ${v}")

    println("-" * 20)

    //2.2 Format 2: Implemented by Fixed Values
    for ((k, 23) <- map1) println(k + " = 23")
  }

}
Zhang San = 23
 King Five = 23
--------------------
Zhang San = 23
 King Five = 23

Process finished with exit code 0

Tags: Scala Big Data Spark

Posted on Sun, 31 Oct 2021 14:47:29 -0400 by bdlang