5
\$\begingroup\$

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
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Nov 20, 2012 at 20:05
\$\endgroup\$
1
  • \$\begingroup\$ Which definition of FizzBuzz are you using? Based on the first Google result the #s are fixed at [1..100], so there shouldn't be any inputs. \$\endgroup\$ Commented Nov 24, 2012 at 19:33

3 Answers 3

6
\$\begingroup\$

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])
answered Nov 21, 2012 at 21:54
\$\endgroup\$
2
  • 5
    \$\begingroup\$ I think mapM (print . fizzBuzz) [0..100] would be better. \$\endgroup\$ Commented Nov 24, 2012 at 21:08
  • 3
    \$\begingroup\$ mapM_ would be even better. \$\endgroup\$ Commented Nov 25, 2012 at 13:44
4
\$\begingroup\$

jaket is definitely right, the pure/impure distinction is important. My addition would be that you should avoid recomputing the modulo:

fizzBuzz :: Int -> String
fizzBuzz n | fizz && buzz = "FizzBuzz"
 | buzz = "Buzz"
 | fizz = "Fizz"
 | otherwise = show n
 where fizz = mod n 3 == 0
 buzz = mod n 5 == 0
sfb = map fizzBuzz [1..15]
answered Nov 22, 2012 at 5:27
\$\endgroup\$
0
2
\$\begingroup\$

I had written something similar to Will, but the spec I read here says, that FizzBuzz should always cover [1..100], so my implementation was a bit different:

show' :: Int -> String
show' n
 | fizz && buzz = "FizzBuzz" 
 | buzz = "Buzz"
 | fizz = "Fizz"
 | otherwise = show n
 where fizz = mod n 3 == 0
 buzz = mod n 5 == 0
fizzBuzz = [show' x | x <- [1..100]]

Will's idea about using where to cache the mod result was a nice idea IMHO.

answered Nov 24, 2012 at 19:40
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.