Your Ad Here

Posted By

rtperson on 06/01/11


Tagged

fizzbuzz


Versions (?)

FizzBuzz in Haskell


 / Published 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.

  1. -- file: Fizz.hs
  2. -- a Haskell implementation of the fizzbuzz problem
  3.  
  4. ns = [0..100] :: [Int]
  5.  
  6. fizz :: Int -> String
  7. fizz n = if (n `mod` 3) == 0 then "fizz" else ""
  8.  
  9. buzz :: Int -> String
  10. buzz n = if (n `mod` 5) == 0 then "buzz" else ""
  11.  
  12. -- a generalized version. It takes the index and the value to divide against, and
  13. -- returns the message if n is evenly divisible by x
  14. fluff :: Int -> Int -> String -> String
  15. fluff n x message = if (n `mod` x) == 0 then message else ""
  16.  
  17. -- a purely functional implementation. Look, no monads!
  18. fizzBuzz :: [String]
  19. fizzBuzz = zipWith (++) (map fizz ns) (map buzz ns)
  20.  
  21. -- List comprehensions, anyone?
  22. boomBang :: [String]
  23. boomBang =
  24. [ if x `mod` 15 == 0
  25. then "boombang"
  26. else if x `mod` 3 == 0
  27. then "boom"
  28. else if x `mod` 5 == 0
  29. then "bang"
  30. else show x
  31. | x <- ns]
  32.  
  33. -- the answer your recruiter is probably looking for
  34. -- (if your recruiter has enough doubts about your
  35. -- programming ability that he/she busts out
  36. -- fizzbuzz on your butt)
  37. main :: IO ()
  38. main = printAll $ map fizz' [1..100]
  39. where
  40. printAll [] = return ()
  41. printAll (x:xs) = putStrLn x >> printAll xs
  42.  
  43. fizz' :: Int -> String
  44. fizz' n
  45. | n `mod` 15 == 0 = "fizzbuzz"
  46. | n `mod` 3 == 0 = "fizz"
  47. | n `mod` 5 == 0 = "buzz"
  48.  
  49. -- or, to get rid of the explicit recursion in the main routine
  50. main2 :: IO ()
  51. main2 = printAll $ map fizz' ns
  52. where
  53. printAll xs = foldr ((>>) . putStrLn) (return ()) xs

Report this snippet  

You need to login to post a comment.