Skip to content

Instantly share code, notes, and snippets.

@ykon
Last active October 19, 2017 13:00
Show Gist options
  • Save ykon/f610b8a9ac8a0e63664577a1c8e74917 to your computer and use it in GitHub Desktop.
Save ykon/f610b8a9ac8a0e63664577a1c8e74917 to your computer and use it in GitHub Desktop.
FizzBuzz in Scala
/*
* Copyright (c) 2017 Yuki Ono
* Licensed under the MIT License.
*/
package func_fizzbuzz
object Main extends App {
def commonFizzBuzz() {
println("commonFizzBuzz:")
var i = 1;
while (i <= 100) {
if (i % 15 == 0)
println("FizzBuzz")
else if (i % 3 == 0)
println("Fizz")
else if (i % 5 == 0)
println("Buzz")
else
println(i)
i += 1
}
}
sealed trait FizzBuzzType { val n: Int }
case class FizzBuzz(n: Int) extends FizzBuzzType
case class Fizz(n: Int) extends FizzBuzzType
case class Buzz(n: Int) extends FizzBuzzType
case class Number(n: Int) extends FizzBuzzType
def toFizzBuzz(number: Int): FizzBuzzType = number match {
case n if n % 15 == 0 => FizzBuzz(n)
case n if n % 3 == 0 => Fizz(n)
case n if n % 5 == 0 => Buzz(n)
case n => Number(n)
}
def toFizzBuzzT(n: Int): FizzBuzzType = {
(n % 3, n % 5) match {
case (0, 0) => FizzBuzz(n)
case (0, _) => Fizz(n)
case (_, 0) => Buzz(n)
case _ => Number(n)
}
}
def toStr(fb: FizzBuzzType): String = fb match {
case FizzBuzz(_) => "FizzBuzz"
case Fizz(_) => "Fizz"
case Buzz(_) => "Buzz"
case Number(n) => n.toString
}
def funcFizzBuzz() {
println("funcFizzBuzz:")
(1 to 100).toList.map(toFizzBuzz).map(toStr).foreach(println)
//(1 to 100).toList.map(toFizzBuzz _ andThen toStr _).foreach(println)
}
def streamFizzBuzz() {
println("streamFizzBuzz:");
Stream.from(1).map(toFizzBuzz).take(100).map(toStr).foreach(println)
//Stream.from(1).map(toFizzBuzz).map(toStr).take(100).foreach(println)
//Stream.from(1).map(toFizzBuzz _ andThen toStr _).take(100).foreach(println)
}
commonFizzBuzz()
//funcFizzBuzz()
//streamFizzBuzz()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment