Created
June 9, 2020 16:57
-
-
Save colindean/47876ae51b592226f41452b4c643e964 to your computer and use it in GitHub Desktop.
A functional, rules-based Fizzbuzz in Scala
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
// 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