Scala Learning(2): map, flatMap, filter與For運算式,scalaflatmap

來源:互聯網
上載者:User

Scala Learning(2): map, flatMap, filter與For運算式,scalaflatmap

本文敘述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[+T] {  def flatMap[U](f: T => List[U]): List[U] = this match {    case x :: xs => f(x) ++ xs.flatMap(f)    case Nil => Nil  }}

filter在List的實現:

abstract class List[+T] {  def filter(p: T => Boolean): List[T] = this match {    case x :: xs =>      if (p(x)) x :: xs.filter(p) else xs.filter(p)    case Nil => Nil  }}
For運算式

下面這段邏輯,可以在for裡簡單表達:

(1 until n) flatMap (i =>  (1 until i) filter (j => isPrime(i + j)) map    (j => (i, j)))
for {  i <- 1 until n  j <- 1 until i  if isPrime(i + j)} yield (i, j)
for與map
for (x <- e1) yield e2// translated toe1.map(x => e2)
for與filter
for (x <- e1 if f; s) yield e2// translated tofor (x <- e1.withFilter(x => f); s) yield e2
for與flatMap
for (x <- e1; y <- e2; s) yield e3// translated toe1.flatMap(x => for (y <- e2; s) yield e3)
for與Pattern Matching

結合前一篇文章(JSON表達)的例子,用for來做map、filter的操作:

val data: List[JSON] = ...for {  JObj(bindings) <- data  JSeq(phones) = bindings("phoneNumbers")  JObj(phone) <- phones  JStr(digits) = phone("number")  if digits startsWith "212"} yield (bindings("firstName"), bindings("lastName"))

for裡面Pattern Matching的大致翻譯過程:

pat <- expr// tox <- expr withFilter {    case pat => true    case _ => false  } map {    case pat => x  }
Exercise
for {  x <- 2 to N  y <- 2 to x  if (x % y == 0)} yield (x, y)

可以翻譯為:

(2 to N) flatMap (x =>  (2 to x) withFilter (y =>    x % y == 0) map (y => (x, y)))

參考自 Principles of Reactive Programming

全文完 :)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.