Skip to content

Instantly share code, notes, and snippets.

@ceedubs
Created October 17, 2012 11:44
Show Gist options
  • Save ceedubs/3905092 to your computer and use it in GitHub Desktop.
Save ceedubs/3905092 to your computer and use it in GitHub Desktop.
Scala FizzBuzz
object FizzBuzz {
val defaultRules = List(
Rule(3, "fizz"),
Rule(5, "buzz")
)
def main(args: Array[String]) = {
fizzBuzz() foreach(println)
}
def fizzBuzz(from: Int = 1, to: Int = 100, rules: Seq[Rule] = defaultRules): Seq[String] = {
(from to to).map { i =>
rules.flatMap { rule =>
if (rule test(i)) Some(rule word) else None
}.reduceLeftOption{_ + _}.getOrElse(i toString)
}
}
case class Rule(factor: Int, word: String) {
def test(x: Int) = x % factor == 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment