Skip to content

Instantly share code, notes, and snippets.

@PiotrCL
Created February 12, 2017 18:58
Show Gist options
  • Save PiotrCL/18918c620a29f403f7bda127d10faa08 to your computer and use it in GitHub Desktop.
Save PiotrCL/18918c620a29f403f7bda127d10faa08 to your computer and use it in GitHub Desktop.
/**
* Methods showing how to transform for/yield based expression into pure map/flatMap/withFilter expression.
* The idea is - this transformations is possible using simple substitutions.
*
* Exapmples based on the coursera "Functional Program Design in Scala"
* Lecture 1.2 "Translation of For"
* https://www.coursera.org/learn/progfun2/lecture/zJcCG/lecture-1-2-translation-of-for
*
* @author Piotr Reszke
*/
case class Book(title: String, authors: List[String])
object ConvertingForToMapFlatMapWithFilter {
val books = List(
Book("title1", List("author1", "author2")),
Book("title2", List("author2", "author3")),
Book("title3", List("author1", "author2", "author3")),
Book("title4", List("author3"))
)
/**
* Base method constructed with for/yield. We want to transform this into map/flatMap/withFilter.
*/
def listBooksByAuthor(author: String) = {
for(b <- books; a <- b.authors if a == author) yield b.title
}
/**
* First step: changing "b <- books" generator from original method into "books.flatMap"
*/
def listBooksByAuthor1(author: String) = {
books.flatMap(b => for (a <- b.authors if a == author) yield b.title)
}
/**
* Second step: change for condition if a == author into b.authors.withFilter
*/
def listBooksByAuthor2(author: String) = {
books.flatMap(b => for (_ <- b.authors.withFilter(a => a == author)) yield b.title)
}
/**
* Third step: change simple for yield into single map call
*/
def listBooksByAuthor3(author: String) = {
books.flatMap (b => b.authors.withFilter(a => a == author) map (_ => b.title))
}
def main(args: Array[String]): Unit = {
println(listBooksByAuthor("author1"))
println(listBooksByAuthor1("author1"))
println(listBooksByAuthor2("author1"))
println(listBooksByAuthor3("author1"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment