Skip to content

Instantly share code, notes, and snippets.

@jesperdj
Created February 29, 2012 10:03
Show Gist options
  • Save jesperdj/1939574 to your computer and use it in GitHub Desktop.
Save jesperdj/1939574 to your computer and use it in GitHub Desktop.
FizzBuzz
-- FizzBuzz in Haskell
import Data.Maybe
fizz x = if x `mod` 3 == 0 then Just "Fizz" else Nothing
buzz x = if x `mod` 5 == 0 then Just "Buzz" else Nothing
ops = [fizz, buzz]
result = map (\x -> let s = concat (mapMaybe ($ x) ops) in if null s then show x else s) [1..100]
// FizzBuzz in Scala with partial functions
val fizz: PartialFunction[Int, String] = { case x if x % 3 == 0 => "Fizz" }
val buzz: PartialFunction[Int, String] = { case x if x % 5 == 0 => "Buzz" }
val ops = Seq(fizz, buzz)
val result = 1 to 100 map { x => (ops collect { case pf if pf isDefinedAt x => pf(x) }).reduceLeftOption(_ + _) getOrElse x.toString }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment