FizzBuzz in Haskell

by Stein Magnus Jodal

I’ve recently started reading the free Haskell tutorial Learn You A Haskell for Great Good! while commuting. So far I’ve enjoyed the tutorial, and I’ve had a couple moments where I’ve smiled to myself on the bus due to typeclasses, etc., which I guess isn’t quite normal behaviour among the general population ;-)

I just discovered that the tutorial is going to be released as a book in a couple of weeks. You should definitely pick it up if you’re interested in learning a different programming language.

Here’s my first shot at some Haskell code, implementing the FizzBuzz kata using guard statements:

fizzBuzz :: Int -> String
fizzBuzz x
    | x `rem` 15 == 0 = "FizzBuzz"
    | x `rem` 3 == 0  = "Fizz"
    | x `rem` 5 == 0  = "Buzz"
    | otherwise       = show x

If you save this code to a file named FizzBuzz.hs, you can load and run it the interactive Haskell interpreter:

$ ghci
Prelude> :l FizzBuzz
[1 of 1] Compiling Main             ( FizzBuzz.hs, interpreted )
Ok, modules loaded: Main.

Now the file is loaded, compiled, and the fizzBuzz function is available in my current namespace. I use a list comprehension and a range to call fizzBuzz 20 times over the integers from 1 to 20, collecting the returned strings in a list:

*Main> [fizzBuzz x | x <- [1..20]]
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz",
"11","Fizz","13","14","FizzBuzz","16","17","Fizz","19","Buzz"]

Updated 2011-04-10: Removed special case for 0, as there is no such rule in FizzBuzz.