Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ]
like image 727
Paul J Avatar asked Nov 27 '22 20:11

Paul J


1 Answers

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.

like image 69
John L Avatar answered Dec 16 '22 02:12

John L