Last active
February 2, 2017 09:45
-
-
Save stsatlantis/3859fc38aae6776ab0346569e0c3901a to your computer and use it in GitHub Desktop.
FizzBuzz with extractors and stackable traits
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
trait Devideable { | |
def isDevidable(i: Int, d: Int, s: String) = if(i % d == 0) Some(s) else None | |
} | |
trait SzogletesDevidable extends Devideable { | |
abstract override def isDevidable(i: Int, d: Int, s: String): Option[String] = super.isDevidable(i, d, s"[$s]") | |
} | |
trait KerekDevidable extends Devideable { | |
abstract override def isDevidable(i: Int, d: Int, s: String): Option[String] = super.isDevidable(i, d, s"($s)") | |
} | |
object FizzBuzz extends SzogletesDevidable with KerekDevidable with Devideable { | |
def unapply(i: Int): Option[String] = isDevidable(i, 15, "FizzBuzz") | |
} | |
object Fizz extends SzogletesDevidable with Devideable { | |
def unapply(i: Int): Option[String] = isDevidable(i, 3, "Fizz") | |
} | |
object Buzz extends Devideable { | |
def unapply(i: Int): Option[String] = isDevidable(i, 5, "Buzz") | |
} | |
object FizzBuzzApp extends App { | |
def playTheGame(i: Int): String = { | |
i match { | |
case FizzBuzz(fb) => fb | |
case Fizz(f) => f | |
case Buzz(b) => b | |
case _ => i.toString | |
} | |
} | |
print((0 until 31).map(playTheGame).mkString(",")) | |
} | |
// output: [(FizzBuzz)],1,2,[Fizz],4,Buzz,[Fizz],7,8,[Fizz],Buzz,11,[Fizz],13,14,[(FizzBuzz)],16,17,[Fizz],19,Buzz,[Fizz],22,23,[Fizz],Buzz,26,[Fizz],28,29,[(FizzBuzz)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment