haskellfizzbuzz

fizzbuzz in haskell?


I'm trying to write 'fizzbuzz' in haskell using list comprehensions.

Why doesn't the following work, and how should it be?

[ if x `mod` 5 == 0 then "BUZZFIZZ"
  if x `mod` 3 == 0 then "BUZZ" 
  if x `mod` 4 == 0 then "FIZZ" | x <- [1..20], 
    x `mod` 3 == 0, 
    x `mod` 4 == 0, 
    x `mod` 5 == 0 ]

Solution

  • First of all, you're missing the else parts of your if expressions. In Haskell, if is an expression, not a statement, so the else part is mandatory.

    Secondly, the list comprehension only produces any values if all the guard expressions evaluate to True. There is no number between 1 and 20 that is 0 modulo 3, 4, and 5, so you'll get no results. You'll want to use || (logical OR) to combine them instead.

    Third, most definitions of FizzBuzz want you to return the number itself if it does not meet any of the other conditions. In that case, you'll want to use show to convert the number to a String.