28. // Scala if for
val ret = if (false) {
"aaa"
} else if (true) {
"bbb"
} else {
"ccc"
}
ret // => "bbb"
29. val list = 1 :: 2 :: 3 :: Nil
val ret = for (i <- list) { i * 2 }
ret //=> Unit
// for
// list.foreach { i => ... }
val list = for (i <- list) yield { i * 2 }
list //=> List(2, 4, 6)
// yield yield
// list.map { i => ... }
30. val num = 42
// match
num match {
case n if n > 40 => println("over 40.")
case _ => println("less than or equal to 40.") // _
}
31.
32. val tuple = (42, "answer")
val (i, s) = tuple
i // 42
s // tuple
// match
tuple match {
case (40, s) => println(s"40 is $s")
case (i, "universe") => println(s"$i is universe")
case (i, s) => println(s"$i is $s")
}
33. val tuple = (42, "hogefuga", 3.14)
tuple match {
case (40, "foobar", 2.718) => //
case (Num, Str, Point) => //
case (`num`, `str`, `p`) => //
case (n: Int, s: String, p: Int) => //
case tup @ (n, s, p) => //
}
34. val list = 1 :: 2 :: 3 :: Nil
// head tail
val head :: tail = list
head // 1
tail // List(2, 3)
list match {
case 42 :: tail => // 42
case head :: Nil => // Nil 1
case e1 :: e2 :: _ => // 2
case Nil => //
}
35. //
val tuple = (42, "answer", 1 :: 2 :: 3 :: Nil)
tuple match {
case (40, str, head :: Nil) =>
case (i, "answer", x :: xs) =>
case (_, _, list @ (head :: tail)) => // list List
case _ => //
}
53. val list = 1 :: 2 :: 3 :: Nil
// 2
val fun = i: Int => i * 2
// map
list.map(fun) //=> List(2, 4, 6)
// List fun
//
list.map(i => i + 2) // List(3, 4, 5)
174. object Main {
def sum(list: List[Double]): Double =
list match {
case Nil => 0
case head :: tail => head + sum(tail)
}
def length(list: List[Double]): Double =
list match {
case Nil => 0
case _ :: tail => 1 + length(tail)
}
def mean(list: List[Double]): Double = sum(list) / length(list)
def main(args: Array[String]): Unit = {
180. def sum(list: List[Double]): Double =
list match {
case Nil => 0
case head :: tail => head + sum(tail)
}
def length(list: List[Double]): Double =
list match {
case Nil => 0
case _ :: tail => 1 + length(tail)
}