Skip to content

Instantly share code, notes, and snippets.

@sbocq
Created November 25, 2012 17:53
Show Gist options
  • Save sbocq/4144549 to your computer and use it in GitHub Desktop.
Save sbocq/4144549 to your computer and use it in GitHub Desktop.
FizzBuzz, without modulo, imperative and functional
// Imperative
var fizzbuzz = 15
var fizz = 3
var buzz = 5
for(i <- 1 to 100) {
val s =
if (i == fizzbuzz) {
fizz = fizzbuzz + 3
buzz = fizzbuzz + 5
fizzbuzz += 15
"FizzBuzz"
} else if (i == fizz) {
fizz += 3
"Fizz"
} else if (i == buzz) {
buzz += 5
"Buzz"
} else i
println(s)
}
// Functional (blows the heap for big i (c.f. scala stream impl)
def unfold[S, A](s:S)(f:S => (S, A)):Stream[A] = {
val (ns, a) = f(s)
Stream.cons(a, unfold(ns)(f))
}
val fb = unfold((1, (15, 3, 5))){
case ((i, s@(fizzbuzz, fizz, buzz))) =>
val (ns, a) = i match {
case `fizzbuzz` =>
((fizzbuzz + 15, fizzbuzz + 3, fizzbuzz + 5), "FizzBuzz")
case `fizz` =>
((fizzbuzz, fizz + 3, buzz), "Fizz")
case `buzz` =>
((fizzbuzz, fizz, buzz + 5), "Buzz")
case _ =>
(s, i)
}
((i + 1, ns), a)
}
fb take(100) foreach println
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment