2
\$\begingroup\$

As the title suggests, this is my FizzBuzz implementation in Scala.

I started learning Scala (and functional programming in general) in small steps about two months ago, and one recent assignment was the FizzBuzz task. Here is the simple code I came up with to solve the problem. It runs perfectly, but I figured CodeReview would be able to easily point out thinks I'm missing.

I do think that the hardcoded magic values (3,5,15,"Fizz","Buzz","FizzBuzz") are slightly problematic, but I'm not sure if that's general consensus or what the best way to handle that is.

FizzBuzz.scala

package fizzbuzz
object FizzBuzz {
 def fizzbuzz(i: Int): String = i match {
 case i if i % 15 == 0 => "FizzBuzz" //because i | 15 is the same as i | 5 and i | 3
 case i if i % 5 == 0 => "Buzz"
 case i if i % 3 == 0 => "Fizz"
 case i => i toString
 }
 def fizzbuzz(start: Int, end: Int): List[String] = (start to end map fizzbuzz) toList
 //assignment requirement: return list of first 100 fizzbuzzed numbers
 def fizzbuzz100(): List[String] = fizzbuzz(1,100)
}

Main.scala (sample usage of FizzBuzz object)

package fizzbuzz
object main {
 def main(args: Array[String]): Unit = {
 FizzBuzz.fizzbuzz100() map println
 }
}
asked Nov 16, 2016 at 22:18
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Although Rosetta Code doesn't always provide the most idiomatic code for each language, look at the "idiomatic solution":

object FizzBuzz extends App {
 1 to 100 foreach { n =>
 println((n % 3, n % 5) match {
 case (0, 0) => "FizzBuzz"
 case (0, _) => "Fizz"
 case (_, 0) => "Buzz"
 case _ => n
 })
 }
}

Your code doesn't use pattern matching well (it is kind of unecesary the way you use it). I would advise you take the solution you have and rewrite it to use pattern matching more like the Rosetta Code solution.

answered Nov 17, 2016 at 1:35
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the pattern matching tip; I was looking for a better way to use it and this is it. \$\endgroup\$ Commented Nov 17, 2016 at 1:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.