Skip to content

FizzBuzzの記述例

mather edited this page Jul 31, 2012 · 2 revisions

命令型で記述した例

for (n <- 1 to 100) {
  if (n % 15 == 0) {
    println("FizzBuzz")
  } else if (n % 3 == 0) {
    println("Fizz")
  } else if (n % 5 == 0) {
    println("Buzz")
  } else {
    println(n)
  }
}

関数型で記述した例

(1 to 100).map {
  case n if (n % 15 == 0) => "FizzBuzz"
  case n if (n % 3  == 0) => "Fizz"
  case n if (n % 5  == 0) => "Buzz"
  case n                  => n.toString
}.foreach(println)