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

这是一个挺能展现Scala编程方式的例子,对正在熟悉Scala这门语言的开发者很有帮助。

Representing JSON

用Scala来表达JSON(Java Script Object Notation)结构,

{
  "firstname" : "John",
  "lastname" : "Smith",
  "address" : {
    "street" : "21 2nd Street",
    "state" : "NY",
    "postalCode" : 10021
  },
  "phoneNumbers" : [
    { "type" : "home", "number" : "212 555-1234" },
    { "type" : "fax", "number : "646 555-4567" }
  ]
}

Scala表示JSON的一种类结构:

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

Example

val data = JObj(Map(
  "firstName" -> JStr("John"),
  "lastName" -> JStr("Smith"),
  "address" -> JObj(Map(
    "street" -> JStr("21 2nd Street"),
    "state" -> JStr("NY"),
    "postalCode" -> JNum(10021)
  )),
  "phoneNumbers" -> JSeq(List(
    JObj(Map(
      "type" -> JStr("home"), "number" -> JStr("212 555-1234")
    )),
    JObj(Map(
      "type" -> JStr("fax"), "number"-> JStr("646 555-4567")
    ))
  ))
))

利用Pattern Matching,展示一个输出JSON string串的方法:

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"
}

参考自 Principles of Reactive Programming

全文完 :)

时间: 2024-08-05 15:22:59

Scala Learning(1): 使用Pattern Matching表达JSON的相关文章

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 pattern matching

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

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] 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)=>"n

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 *

Scala learning(2): map, flatMap, filter与For表达式

本文叙述Collections里最常见的三种操作map, flatMap, filter,与For表达式的关系. List对三种方法的实现 map在List的实现: abstract class List[+T] { def map[U](f: T => U): List[U] = this match { case x :: xs => f(x) :: xs.map(f) case Nil => Nil } } flatMap在List的实现: abstract class List[

How Scala killed the Strategy Pattern

How Scala killed the Strategy Pattern By Alvin Alexander. Last updated: Mar 23, 2014 table of contents [hide] The OOP Strategy Pattern Two immediate thoughts How Scala killed the Strategy Pattern Understanding the 'execute' method Dude, you used 'met

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

Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final) A. Single Wildcard Pattern Matching B. Pair of Toys C. Bracket Subsequence D. Array Restoration-区间查询最值(RMQ(ST))

Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final) A. Single Wildcard Pattern Matching 题意就是匹配字符的题目,打比赛的时候没有看到只有一个" * ",然后就写挫了,被hack了,被hack的点就是判一下只有一个" * ". 1 //A 2 #include<iostream> 3 #include<cstdio&g