You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cheat.sheets/sheets/_scala/ControlStructures

72 lines
1.7 KiB
Plaintext

// conditional
if (check) happy else sad
// conditional sugar
if (check) happy // same as
if (check) happy else ()
// multiple conditions
if (check) happy else if(secondCheck) lessHappy else ()
// while loop
while (x < 5) { println(x); x += 1}
// do while loop.
do { println(x); x += 1} while (x < 5)
// break
// slides: https://www.slideshare.net/Odersky/fosdem-2009-1013261/21
import scala.util.control.Breaks._
breakable {
for (x <- xs) {
if (Math.random < 0.1) break
}
}
// 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
// http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax
for (x <- xs; y <- ys) {
println("%d/%d = %.1f".format(x, y, x/y.toFloat))
}
// 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)
}
// recursion
// can yield a "java.lang.StackOverflowError" with large lists
// this is because each recursive call of the function is waiting for the evaluation of the next
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case x :: tail => x + sum(tail)
}
// tail recursion
// this type of recursion will not throw StackOverflowError
// this is because each recursive call of the function is fully evaluated
def sum(ints: List[Int], accum: Int): Int = ints match {
case Nil => accum
case x :: tail => sum(tail, accum + x)
}