Skip to content

Instantly share code, notes, and snippets.

@fluency03
Last active July 13, 2016 11:18
Show Gist options
  • Save fluency03/2c41628df42164ccd8ea324c39a3e469 to your computer and use it in GitHub Desktop.
Save fluency03/2c41628df42164ccd8ea324c39a3e469 to your computer and use it in GitHub Desktop.
/**
* This is a Scala script: scala-for.scala
*/
val xs: Array[Int] = Array(1, 2, 3)
val ys: Array[Int] = Array(1, 2, 3, 4, 5)
/** for comprehension: filter/map */
for (x <- xs if x % 2 == 0)
yield x * 10
/** same as */
xs.filter(_ % 2 == 0).map(_ * 10)
/** for comprehension: destructuring bind */
for ((x,y) <- xs.zip(ys))
yield x * y
/** same as */
(xs.zip(ys)).map { case (x, y) => x * y }
/** for comprehension: cross product */
for (x <- xs; y <- ys)
yield x * y
/** same as */
xs.flatMap { x => ys.map {y => x * y} }
/** for comprehension: imperative-ish sprintf-style */
for (x <- xs; y <- ys) {
println("%d * %d = %d".format(x, y, x * y))
}
/** for comprehension: iterate including the upper bound */
for (i <- 1 to 5) {
println(i)
}
/** for comprehension: iterate omitting the upper bound */
for (i <- 1 until 5) {
println(i)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment