Skip to content

Instantly share code, notes, and snippets.

@j5ik2o
Created April 29, 2011 15:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j5ik2o/948503 to your computer and use it in GitHub Desktop.
Save j5ik2o/948503 to your computer and use it in GitHub Desktop.
FizzBuzzを命令型と関数型で比較

命令型で記述。

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)
  }
}

関数型で記述。その前に

scala> 1.to(100)
res0: scala.collection.immutable.Range.Inclusive = Range(1, ..., 100)
scala> res0.map({v :Int => v * 2})
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(2, ..., 200)
 val f = {n:Int => n.toString}
 /*
 val f = new Function1[Int,String]{
   def apply(arg:Int):String = arg.toString
 }
*/
 (1 to 100).map(f)
res0.map{v :Int => v * 2}
res0.map{v => v * 2}
res0.map{_ * 2}
res0.map(_ * 2)

関数型で記述。

(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
}).foreach(println)

他の書き方

 (1 to 100).map {
   n => if (n % 15 == 0) "FizzBuzz"
     else if (n % 3 == 0) "Fizz"
       else if (n % 5 == 0) "Buzz"
         else n
}.foreach(println)
(1 to 100).map {
  case n => if (n % 15 == 0) "FizzBuzz"
    else if (n % 3 == 0) => "Fizz"
      else if (n % 5 == 0) => "Buzz"
        else n
}.foreach(println)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment