Skip to content

Instantly share code, notes, and snippets.

@dsebban
Last active April 17, 2019 17:06
Show Gist options
  • Save dsebban/c38123bb6ff94cc3e170928f49e6a6f9 to your computer and use it in GitHub Desktop.
Save dsebban/c38123bb6ff94cc3e170928f49e6a6f9 to your computer and use it in GitHub Desktop.
FizzBuzz using monoids
import $ivy.`org.typelevel::cats-core:1.6.0`, cats.implicits._
def rule[A](n: Int, default: A): Int => Option[A] = x => if ( x % n == 0) default.some else None
val fizz = rule(3,"Fizz")
val buzz = rule(5,"Buzz")
val boom = rule(7,"Boom")
def fizzBuzz(rules: List[Int => Option[String]]): List[Int] => List[String] = xs => {
val rule: Int => Option[String] = rules.foldMap(identity)
xs.map(x => rule(x).getOrElse(x.show))
}
fizzBuzz(List(fizz,buzz,boom))((1 to 100).toList)
//res4: List[String] = List(
// "1",
// "2",
// "Fizz",
// "4",
// "Buzz",
// "Fizz",
// "Boom",
// "8",
// "Fizz",
// "Buzz",
// "11",
// "Fizz",
// "13",
// "Boom",
// "FizzBuzz",
// "16",
// "17",
// "Fizz",
// "19",
// "Buzz",
// "FizzBoom",
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment