Skip to content

Instantly share code, notes, and snippets.

@colindean
Created June 9, 2020 16:57
Show Gist options
  • Save colindean/47876ae51b592226f41452b4c643e964 to your computer and use it in GitHub Desktop.
Save colindean/47876ae51b592226f41452b4c643e964 to your computer and use it in GitHub Desktop.
A functional, rules-based Fizzbuzz in Scala
// functional, rules-based fizzbuzz
// inspired heavily by http://boston.conman.org/2020/06/08.1
def fizzbuzz(num: Int): String = {
def ifElse(matchNum: Int, ifMatch: String, otherwise: String => String): String => String = {
if (num % matchNum == 0) {
_ => ifMatch + otherwise("")
} else {
otherwise
}
}
def fizz(otherwise: String => String) = ifElse(3, "Fizz", otherwise)
def buzz(otherwise: String => String) = ifElse(5, "Buzz", otherwise)
//fizz(buzz(identity))(num.toString)
// rules always seem to change
val rules = List(
fizz(_),
buzz(_)
)
// composing the rules makes the world flexible
val engine = rules.reduce(_.compose(_))(identity)
engine(num.toString)
}
1.to(100).foreach(n => println(s"$n: ${fizzbuzz(n)}"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment