What is the essence of scala pattern matching? -Starting from responsive programming of Coursera

Source: Internet
Author: User
We recommend the responsive programming course on Coursera, an advanced Scala language course. At the beginning of the course, we proposed an Application Scenario: constructing a JSON string. If you do not know the JSON string, you can simply Google it. To do this, we define the following classes
abstract class JSON case class JSeq(elems: List[JSON]) extends JSON  case class JObj(bindings: Map[String, JSON]) extends JSON case class JNum(num: Double) extends JSON case class JStr(str: String) extends JSON case class JBool(b: Boolean) extends JSON case object JNull extends JSON

 

Next, we construct a JSON object.
val data = JObj(Map(    "firstName" -> JStr("John"),    "lastName" -> JStr("Smith"),    "address" -> JObj(Map(      "streetAddress" -> JStr("21 2nd street"),      "state" -> JStr("NY"),      "postalCode" -> JNum(10021)    )),    "phoneNumbers" -> JSeq(List(      JObj(Map(        "type" -> JStr("home"), "number" -> JStr("211 555-1234")      )),      JObj(Map(        "type" -> JStr("fax"), "number" -> JStr("646 555-4567")      ))    ))  ))

  

Then display the JSON
def show(json: JSON): String = json match {    case JSeq(elems) =>      "[" + (elems map show mkString ", ") + "]"    case JObj(bindings) =>      val assocs = bindings.map {        case (key, value) => "\"" + key + "\": " + show(value)      }      "{" + (assocs mkString ", ") + "}"    case JNum(num) => num.toString    case JStr(str) => ‘\"‘ + str + ‘\"‘    case JBool(b) => b.toString    case JNull => "null"  }

 

The result is as follows:
{    "firstName": "John",    "lastName": "Smith",    "address": {        "streetAddress": "21 2nd street",        "state": "NY",        "postalCode": 10021    },    "phoneNumbers": [        {            "type": "home",            "number": "211 555-1234"        },        {            "type": "fax",            "number": "646 555-4567"        }    ]}

This section is worth pondering:

{Case (Key, value) => "\" "+ key +" \ ":" + show (value)} {Case (Key, value) => "\" "+ key +" \ ":" + show (value)} What type is it? How is this code combined with the preceding map?

The code itself is not a type.

Open the definition of the map function and see map [B, that] (F: A => B). This means that when you input A, B is given.

For the above map, the expected input should be jbinding (we define type jbinding = (string, JSON), and the output string; that is, jbinding => string

Let's take a look at the symbol =>, which is actually a function that represents a => B is a function. In fact, the format of a = "B" is short for Scala function1. Then the above jbinding => string is scala. function1 [jbinding, string]

Continue with the definition of trait function1 (apply method, the entrance to Heaven ).

Trait function1 [-a, + R] {

Def apply (X: a): R

}

During pattern matching, {Case (Key, value) => "\" "+ key +" \ ":" + show (value)} is translated

New function1 [jbinding, string] {

Def apply (X: jbinding) = x match {

Case (key, value) => key + ";" + show (value)

}

}

Then everyone can understand it, right?

 

Finally, in Scala syntax, all pattern matching is attributed to the matching of the apply method, and everything can be viewed according to the inherent thinking.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.