Created
December 12, 2016 11:21
-
-
Save MaximeKjaer/77470b143207f21f6a68317600e410cb to your computer and use it in GitHub Desktop.
Desugaring various for-expressions in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** EXAMPLE 1 | |
* From the 2015 Scala final, exercise 3 | |
* http://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/prev-exams/final-2015.pdf | |
*/ | |
// For-expresion | |
for { | |
msg <- acc | |
msg2 <- doAction(elem) | |
} yield { | |
msg ++ List(msg2) | |
} | |
// Desugared | |
acc flatMap { msg => | |
doAction(elem) map { msg2 => | |
msg ++ List(msg2) | |
} | |
} | |
/** EXAMPLE 2 | |
* From the 2014 Scala final, exercise 1 | |
* http://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/prev-exams/final-2014.pdf | |
*/ | |
// For-expression | |
for (m <- movies) yield | |
m.title + ", directed by " + m.director + " (" + (2014 - m.releaseDate) + " years ago)" | |
// Desugared | |
movies map { m => | |
m.title + ", directed by " + m.director + " (" + (2014 - m.year) + " years ago)" | |
} | |
// For-expression | |
for { | |
m <- movies | |
if m.leadActors contains "Philip Seymour Hoffman" | |
} yield m.title | |
// Desugared | |
movies | |
.filter((m: Movie) => m.leadActors contains "Philip Seymour Hoffman") | |
.map((m : Movie) => m.title) | |
// For-expression | |
for { | |
m1 <- movies | |
director = m1.director | |
m2 <- movies | |
if m2.leadActors contains director | |
} yield (director, m2.title) | |
// Desugared | |
movies flatMap { m1 => | |
val director = m1.director | |
movies | |
.filter(_.leadActors contains director) | |
.map { m2 => (director, m2.title) } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment