Difference between revisions of "Haskell Quiz/FizzBuzz/Solution Ninju"
< Haskell Quiz | FizzBuzz
Jump to navigation
Jump to search
Line 1: | Line 1: | ||
[[Category:Haskell Quiz solutions|FizzBuzz]] |
[[Category:Haskell Quiz solutions|FizzBuzz]] |
||
− | 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. |
+ | 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) |
<haskell> |
<haskell> |
||
Line 17: | Line 17: | ||
| n `mod` 3 == 0 = "Buzz" |
| n `mod` 3 == 0 = "Buzz" |
||
| otherwise = show n |
| otherwise = show n |
||
+ | </haskell> |
||
+ | |||
+ | An alternate solution: |
||
+ | |||
+ | <haskell> |
||
+ | module Main where |
||
+ | |||
+ | main :: IO () |
||
+ | main = do |
||
+ | mapM_ putStrLn $ zipWith xor fizzbuzz $ map show [1..100 :: Int] |
||
+ | where |
||
+ | loop n s = cycle $ replicate (n-1) "" ++ [s] |
||
+ | fizzbuzz = zipWith (++) (loop 3 "Fizz") (loop 5 "Buzz") |
||
+ | xor s t = if null s then t else s |
||
</haskell> |
</haskell> |
Revision as of 14:10, 6 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 = do
mapM_ putStrLn $ zipWith xor fizzbuzz $ map show [1..100 :: Int]
where
loop n s = cycle $ replicate (n-1) "" ++ [s]
fizzbuzz = zipWith (++) (loop 3 "Fizz") (loop 5 "Buzz")
xor s t = if null s then t else s