HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

FizzBuzz up to 99 in Haskell

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
haskellfizzbuzzstackoverflow

Problem

This code solves the problem of FizzBuzz. Is it possible in any way to improve it?

main = main' 1 where
main' n = do
    (putStrLn . choose) (show n, "Fizz", "Buzz", "FizzBuzz", n)
    if n < 100 then main' (succ n) else putStrLn "End!" 
    where
        choose (n0, n3, n5, n15, n) 
            | mod n 3 == 0 && mod n 5 == 0 = n15
            | mod n 5 == 0 = n5
            | mod n 3 == 0 = n3
            | True = n0

Solution

You could separate your I/O from the pure code:

fizzBuzz :: Int -> String
fizzBuzz n | mod n 3 == 0 && mod n 5 == 0 = "FizzBuzz"
           | mod n 5 == 0                 = "Buzz"
           | mod n 3 == 0                 = "Fizz"
           | otherwise                    = show n

main = mapM print (map fizzBuzz [0..100])

Code Snippets

fizzBuzz :: Int -> String
fizzBuzz n | mod n 3 == 0 && mod n 5 == 0 = "FizzBuzz"
           | mod n 5 == 0                 = "Buzz"
           | mod n 3 == 0                 = "Fizz"
           | otherwise                    = show n

main = mapM print (map fizzBuzz [0..100])

Context

StackExchange Code Review Q#18852, answer score: 6

Revisions (0)

No revisions yet.