Skip to content

Instantly share code, notes, and snippets.

@channingwalton
Created October 4, 2012 20:03
Show Gist options
  • Save channingwalton/3836057 to your computer and use it in GitHub Desktop.
Save channingwalton/3836057 to your computer and use it in GitHub Desktop.
FizzBuzz with Scalaz
// Inspired by http://dave.fayr.am/posts/2012-10-4-finding-fizzbuzz.html
object FizzBuzz extends App {
import scalaz._
import Scalaz._
def fizzbuzz(i: Int) = ((i % 3 == 0) option "fizz") |+| ((i % 5 == 0) option "buzz") | i.shows
for (i <- 1 to 100) {println(i + " " + fizzbuzz(i))}
}
@etorreborre
Copy link

I guess that's what @dibblego meant when he wrote that Semigroup[B]: A => B was also a semi-group:

def on(mod: Int, name: String) = (i: Int) => (i % mod == 0) option name
def emit = on(3, "fizz") |+| on(5, "buzz")
def fizzbuzz = (i: Int) => emit(i) | i.shows

@etorreborre
Copy link

Or maybe with a fold:

def on(mod: Int, name: String) = (i: Int) => (i % mod == 0) option name
def emit = List((3, "fizz"),
                 (5, "buzz")).map((on _).tupled).sumr

def fizzbuzz = (i: Int) => emit(i) | i.shows

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment