Personal tools

Haskell Quiz/FizzBuzz/Solution Ninju

From HaskellWiki

< Haskell Quiz | FizzBuzz(Difference between revisions)
Jump to: navigation, search
Line 25: Line 25:
   
 
main :: IO ()
 
main :: IO ()
main = do
+
main = mapM_ putStrLn $ zipWith3 join (loop 3 "Fizz") (loop 5 "Buzz") [1..100]
mapM_ putStrLn $ zipWith3 join (loop 3 "Fizz") (loop 5 "Buzz") [1..100 :: Int]
 
 
where
 
where
loop n s = cycle $ replicate (n-1) "" ++ [s]
+
loop n s = cycle $ replicate (n-1) [] ++ [s]
join s t n = head $ filter (not . null) [s ++ t, show n]
+
join s t n = head $ filter (not . null) [s ++ t, show (n :: Int)]
 
</haskell>
 
</haskell>

Revision as of 06:09, 7 July 2010


I think this is probably what I'd do in the interview situation - i.e. the first and most obvious thing that comes to mind. (Alex Watt)

module Main where
 
main :: IO ()
main = printAll $ map fizzBuzz [1..100]
       where
       printAll [] = return ()
       printAll (x:xs) = putStrLn x >> printAll xs
 
fizzBuzz :: Integer -> String
fizzBuzz n | n `mod` 15 == 0 = "FizzBuzz"
           | n `mod` 5  == 0 = "Fizz"
           | n `mod` 3  == 0 = "Buzz"
           | otherwise       = show n

An alternate solution:

module Main where
 
main :: IO ()
main = mapM_ putStrLn $ zipWith3 join (loop 3 "Fizz") (loop 5 "Buzz") [1..100]
  where
    loop n s = cycle $ replicate (n-1) [] ++ [s]
    join s t n = head $ filter (not . null) [s ++ t, show (n :: Int)]