Friday, August 22, 2014

Haskell Coding Kata I: FizzBuzz

At the end of the Haskell programming series II, I proposed the readers a coding Kata. FizzBuzz is a very simple problem:

Given a number N, if the number is multiple of 3 print Fizz, if the number is multiple of 5 print Buzz, if the number is multiple of both print FizzBuzz. Nothing really fancy. As promised, here you have one possible solution for a little variation of the problem, in Haskell:

module Main where  
 
main :: IO()  
main = do  
   putStrLn "Enter a number"  
   nb <- readLn  
   fizzBuzz nb  
   main  

fizzBuzz :: Int -> IO()  
fizzBuzz x = do  
   if (x `mod` 3 == 0) then putStrLn "Fizz" else return ()  
   if (x `mod` 5 == 0) then putStrLn "Buzz" else return ()  

A more elaborated solution that prints the first N FizzBuzz executions could be as follows:

module Main where  
main :: IO()  
main = do  
   putStrLn "Enter a number"  
   nb <- readLn  
   putStrLn $ show $ map fizzBuzz $ take nb [1,2..]  
   main  

fizzBuzz :: Int -> String  
fizzBuzz x =  
   if (fb == "") then show x else fb  
   where fb = fizz x ++ buzz x  

fizz :: Int -> String  
fizz = matchModule 3 "Fizz"  

buzz :: Int -> String  
buzz = matchModule 5 "Buzz"  

matchModule :: Int -> String -> Int -> String  
matchModule modulo message nb  
   | nb `mod` modulo == 0 = message  
   | otherwise = ""  

The output of an execution is as follows (using ghci):

 > ghci  
 GHCi, version 7.6.3 [NG/7.6.3.5]: http://www.haskell.org/ghc/ :? for help  
 Loading package ghc-prim ... linking ... done.  
 Loading package integer-gmp ... linking ... done.  
 Loading package base ... linking ... done.  
 Prelude> :load Main.hs   
 [1 of 1] Compiling Main       ( Main.hs, interpreted )  
 Ok, modules loaded: Main.  
 *Main> main  
 Enter a number  
 15  
 ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]  
 Enter a number  
 9  
 ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz"]  
 Enter a number  

Happy Haskell!