FizzBuzz(Nパターン)をScalaで
お題:FizzBuzz(Nパターン) - No Programming, No Life
こちらのお題にScalaで挑戦。手続き脳が頑固で苦戦しました。
object FizzBuzzN { def main(args : Array[String]) : Unit = { fizzBuzzN(List(3, "Fizz", 5, "Buzz", 7, "Hoge"),100).foreach(s => println(s)) } def fizzBuzzN(rule : List[_], count : Int) : List[String] = { def conv(c : String, x : Int, pr : List[_]) : String = { pr match { case n::s::pt => if (x % n.toString.toInt == 0) conv(c + s.toString, x, pt) else conv(c, x, pt) case _ => if (c == "") x.toString else c } } (1 to count).toList.map(x => conv("", x, rule)) } }
(8/16 追記)
toString.toInt とか汚いので少し書きなおし
object FizzBuzzN { def main(args: Array[String]): Unit = { fizzBuzzN(List(3, "Fizz", 5, "Buzz", 7, "Hoge"), 100).foreach(println(_)) } def fizzBuzzN(rule: List[_], count: Int): List[String] = { def conv(c: String, x: Int, pr: List[_]): String = pr match { case (n: Int) :: (s: String) :: pt if (x % n == 0) => conv(c + s, x, pt) case n :: s :: pt => conv(c, x, pt) case _ => if (c == "") x.toString else c } (1 to count).toList.map(conv("", _, rule)) } }