Scala Learning (2): Map, FlatMap, filter and for expressions

Source: Internet
Author: User

This paper describes the three most common operations map, FLATMAP, filter, and the relationship of the for expression in collections.

The implementation of list on three kinds of methods

Map in the implementation of list:

abstractclass List[+T] {  defthismatch {    case x :: xs => f(x) :: xs.map(f)    case Nil => Nil  }}

The implementation of FLATMAP in list:

abstractclass List[+T] {  defthismatch {    case x :: xs => f(x) ++ xs.flatMap(f)    case Nil => Nil  }}

Filter in the implementation of the list:

abstractclass List[+T] {  defthismatch {    case x :: xs =>      ifelse xs.filter(p)    case Nil => Nil  }}
for-expression

The following logic can be simply expressed in for:

(1 until n) flatMap (i =>  (1 until i) filter (j => isPrime(i + j)) map    (j => (i, j)))
for {  1 until n  1 until i  ifyield (i, j)
For and map
foryield e2// translated toe1.map(x => e2)
For and filter
forifyield e2// translated toforyield e2
For and Flatmap
foryield e3// translated toforyield e3)
For and pattern Matching

In conjunction with an example of a previous article (JSON expression), use for to do map, filter operations:

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

For inside pattern matching the approximate translation process:

pat <- expr// tox <- expr withFilter {    casetrue    casefalse  } map {    case pat => x  }
Exercise
for {  2 to N  2 to x  if0yield (x, y)

Can be translated as:

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

Reference from principles of reactive programming

Complete the full text:)

Scala Learning (2): Map, FlatMap, filter and for expressions

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.