Skip to content

Instantly share code, notes, and snippets.

@bkyrlach
Last active August 29, 2015 14:01
Show Gist options
  • Save bkyrlach/34422818f4f359554d3c to your computer and use it in GitHub Desktop.
Save bkyrlach/34422818f4f359554d3c to your computer and use it in GitHub Desktop.
Yet another FizzBuzz implementation...
// After reading the trials and tribulations here
// http://www.learningclojure.com/2014/05/fizz-buzz-interview-question.html?utm_source=dlvr.it&utm_medium=twitter
// I decided to see how easy this is using sum types.
// Answer: Pretty easy. :D
sealed trait \/[+L, +R]
case class \[L](l: L) extends \/[L, Nothing]
case class /[R](r: R) extends \/[Nothing, R]
object Program {
def numbers(n: Int): Stream[Int] = Stream.cons(n, numbers(n + 1))
def transformIf[L,R](e: \/[L, R])(p: L => Boolean)(f: L => R): \/[L, R] = e match {
case \(l) => if(p(l)) /(f(l)) else \(l)
case /(r) => /(r)
}
def main(args: Array[String]): Unit = {
numbers(1).take(100)
.map(\(_))
.map(transformIf(_)(_ % 15 == 0)(_ => "fizzbuzz"))
.map(transformIf(_)(_ % 5 == 0)(_ => "buzz"))
.map(transformIf(_)(_ % 3 == 0)(_ => "fizz")).toList.foreach(println)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment