Scala
for
がすごい
flatMap、filter、foreach、mapを使ったコードに脱糖されるらしい
scala// map
for (n <- 1 to 10) yield n * 2
// filter
for (n <- 1 to 10 if n % 2 == 0) yield n
// ジェネレータ2個をループしてタプル
for (x <- 0 to 9; y <- 0 to 9) yield (x, y)
// ジェネレータ2個をループして2つの値が一致していないところでタプル
for (x <- 0 to 9; y <- 0 to 9 if x != y) yield (x, y)
scaladef head[T](list: List[T]): Option[T] =
list match
case h :: _ => Some(h)
case _ => None
def div(a: Int, b: Int): Option[Int] =
if b == 0 then None else Some(a / b)
@main def main(): Unit =
val z = for
x <- head(List(1, 2, 3))
y <- div(x, 2)
yield y
println(z)