Last active
October 16, 2015 16:18
-
-
Save nenono/9f388b07c3c1c97effd0 to your computer and use it in GitHub Desktop.
ScalaでFizzBuzz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// フィズバズ | |
object FizzBuzz{ | |
def fizzBuzz(max: Int) = { | |
require(max > 0) // assertion | |
(1 to max) // 1~(max-1)のシーケンス生成。1 to maxの箇所は、オブジェクトの1引数メソッドの糖衣構文で、1.to(max)と同じ意味 | |
.map( // お馴染みmap関数はLINQ風にメソッド呼び出し | |
(x: Int) => // lambda式もC#風と思うとわかりやすいです | |
(x % 3, x % 5) match { // タプル生成→パターンマッチで分岐する形はF#(ML)っぽく書けます | |
case (0, 0) => "FizzBuzz!" | |
case (0, _) => "Fizz!" | |
case (_, 0) => "Buzz!" | |
case (_, _) => x.toString // 引数の無いメソッドは、括弧を付けずに呼び出すこともできます | |
}) | |
.foreach(println(_)) // foreachもLINQ風、println(_)はラムダ式の省略構文で、(x)=>println(x)と同じ意味 | |
} | |
def main(args: Array[String]): Unit = { | |
fizzBuzz(100) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment