Created
October 17, 2012 11:44
-
-
Save ceedubs/3905092 to your computer and use it in GitHub Desktop.
Scala FizzBuzz
This file contains hidden or 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
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