HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajor

First Scala FizzBuzz implementation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
scalaimplementationfirstfizzbuzz

Problem

Would love some feedback on this. I'm coming from a Java background and kinda feel like I've just done exactly what I would do in Java. Is there a better way?

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

Solution

Or if you prefer match/case to if/else:

(1 until 100).map(i => (i % 3, i % 5) match {
  case (0, 0) => "FizzBuzz"
  case (0, _) => "Fizz"
  case (_, 0) => "Buzz"
  case _ => i
}).foreach(println)


Update:

So what we are doing here is taking list of numbers and mapping them first to tuples where on the left side is that number module 3 and on the right side modulo 5. Then we are matching those tuples to cases where both are zero, left is zero, right is zero or neither is zero.

Also the actual logic is in the map-block and side-effect of printing is in the foreach-block.

Code Snippets

(1 until 100).map(i => (i % 3, i % 5) match {
  case (0, 0) => "FizzBuzz"
  case (0, _) => "Fizz"
  case (_, 0) => "Buzz"
  case _ => i
}).foreach(println)

Context

StackExchange Code Review Q#40656, answer score: 47

Revisions (0)

No revisions yet.