Skip to content

Instantly share code, notes, and snippets.

@jvz
Last active September 24, 2023 21:11
Show Gist options
  • Save jvz/ca4e4b246d9fbd7478fa06d094d3f979 to your computer and use it in GitHub Desktop.
Save jvz/ca4e4b246d9fbd7478fa06d094d3f979 to your computer and use it in GitHub Desktop.
Functional FizzBuzz
// adapted from this great paper:
// https://themonadreader.files.wordpress.com/2014/04/fizzbuzz.pdf
def fb(n: Int): String = {
def test(d: Int, s: String)(x: String ⇒ String)(v: String): String =
if (n % d == 0) s + x("") else x(v)
(test(3, "fizz") _ compose test(5, "buzz"))(identity)(n.toString)
}
def fizzbuzz(n: Int): Seq[String] =
for (i ← 1 to n) yield fb(i)
def main(args: Array[String]): Unit =
println(fizzbuzz(args(0).toInt).mkString("\n"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment