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 ]
First of all, you’re missing the
elseparts of yourifexpressions. In Haskell,ifis an expression, not a statement, so theelsepart 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
showto convert the number to aString.