To write a for loop to work like a map method, add a yield statement to the end of the loop.
val result = for {
c <- "hello, world"
if c != 'l'
} yield c.toUpper
Adding yield to a for loop essentially places the result from each loop iteration into a temporary holding area. When the loop completes, all of the elements in the holding area are returned as a single collection.
Whereas the map or for/yield approaches are used to transform one collection into another, the foreach method is typically used to operate on each element without returning a result.
For example,
val p = (1 to 20).toList
for (k<-p if k %3 == 0) yield("<"+k+">")
vs.
p.filter(_ % 3 == 0).map(x=> "<"+x+">")
The conditioins in for comprehension are converted into a call to withFilter instead of filter. If filter were used, it would create an intermediate collection for each condition applied. The withFilter combinator delays evaluation until absolutely nessary. For a chain of withFilter calls, each withFilter invocation passes down a view to the next withFilter in line.
For example,
val p = (1 to 20).toList
for (k<-p if k %3 == 0) yield("<"+k+">")
vs.
p.filter(_ % 3 == 0).map(x=> "<"+x+">")
The conditioins in for comprehension are converted into a call to withFilter instead of filter. If filter were used, it would create an intermediate collection for each condition applied. The withFilter combinator delays evaluation until absolutely nessary. For a chain of withFilter calls, each withFilter invocation passes down a view to the next withFilter in line.
No comments:
Post a Comment