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 ]
This isn't valid Haskell. The else
branch is not optional in if ... then ... else
. Rather than using if
, this seems like a good opportunity to use a case
statement.
case (x `rem` 3, x `rem` 5) of
(0,0) -> "fizzbuzz"
(0,_) -> "fizz"
(_,0) -> "buzz"
_ -> show x
This snippet will work for a traditional "fizzbuzz"; your code seems to be slightly different.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With