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