Last active
July 1, 2016 12:19
-
-
Save khajavi/1463b946f578b4dde5125349e52f2e27 to your computer and use it in GitHub Desktop.
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
object forTranslationRules extends App { | |
val l1 = 1 to 4 | |
val l2 = 3 to 7 | |
val l3 = 2 to 8 | |
// Simple generator | |
val a1 = for (a <- l1) yield a * 2 | |
val a2 = l1 map (_ * 2) | |
assert(a1 == a2) | |
// Sequence of generators | |
val b1 = for (a <- l1; b <- l2) yield (a, b) | |
val b2 = l1.flatMap(x => l2.map(y => (x, y))) | |
assert(b1 == b2) | |
// generators with guards | |
val c1 = for (a <- l1; if a % 2 == 0) yield a * 2 | |
val c2 = l1.withFilter(_ % 2 == 0).map(_ * 2) | |
assert(c1 == c2) | |
def f(a: Int) = List(a * 2) | |
def g(a: Int) = List(a * 3) | |
val d1 = for (x <- l1; | |
y <- f(x); | |
z <- g(y)) yield z | |
val d2 = for (y <- for (x <- l1; y <- f(x)) yield y; | |
z <- g(y)) yield z | |
val d3 = l1.flatMap(x => f(x).flatMap(y => g(y))) | |
assert(d1 == d2) | |
assert(d2 == d3) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment