DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
FizzBuzz In Haskell
// The dread FizzBuzz question -- really, a test if your average programmer knows his or her FOR loops.
// The spec is that you're counting from 1 to 100. Your program should print out "fizz" if the index is divisible
// by three, and "buzz" if it's divisible by five, and "fizzbuzz" if it's divisible by both.
//
// I have a couple different versions in this code: first, a few functions just fizzing or buzzing
// Second, a generalization which allows any standard message against any divisor.
// Third, a purely functional version that zips two lists together (giving us free concatenation for "fizzbuzz")
// Fourth, a list comprehension
// and lastly, a monadic version that calls a pure function that uses guards
// This Haskell version does little more than pack together a list with is accessible by index, and hands back "fizz" or "buzz"
// as appropriate. The first several functions are just me playing around with it.
-- file: Fizz.hs
-- a Haskell implementation of the fizzbuzz problem
ns = [0..100] :: [Int]
fizz :: Int -> String
fizz n = if (n `mod` 3) == 0 then "fizz" else ""
buzz :: Int -> String
buzz n = if (n `mod` 5) == 0 then "buzz" else ""
-- a generalized version. It takes the index and the value to divide against, and
-- returns the message if n is evenly divisible by x
fluff :: Int -> Int -> String -> String
fluff n x message = if (n `mod` x) == 0 then message else ""
-- a purely functional implementation. Look, no monads!
fizzBuzz :: [String]
fizzBuzz = zipWith (++) (map fizz ns) (map buzz ns)
-- List comprehensions, anyone?
boomBang :: [String]
boomBang =
[ if x `mod` 15 == 0
then "boombang"
else if x `mod` 3 == 0
then "boom"
else if x `mod` 5 == 0
then "bang"
else show x
| x <- ns]
-- the answer your recruiter is probably looking for
-- (if your recruiter has enough doubts about your
-- programming ability that he/she busts out
-- fizzbuzz on your butt)
main :: IO ()
main = printAll $ map fizz' [1..100]
where
printAll [] = return ()
printAll (x:xs) = putStrLn x >> printAll xs
fizz' :: Int -> String
fizz' n
| n `mod` 15 == 0 = "fizzbuzz"
| n `mod` 3 == 0 = "fizz"
| n `mod` 5 == 0 = "buzz"
| otherwise = show n
-- or, to get rid of the explicit recursion in the main routine
main2 :: IO ()
main2 = printAll $ map fizz' ns
where
printAll xs = foldr ((>>) . putStrLn) (return ()) xs





