I'm still learning Haskell, and I was wondering if there is a less verbose way to express the below statement using 1 line of code:
map (\x -> (x, (if mod x 3 == 0 then "fizz" else "") ++
if mod x 5 == 0 then "buzz" else "")) [1..100]
Produces:
[(1,""),(2,""),(3,"fizz"),(4,""),(5,"buzz"),(6,"fizz"),(7,""),(8,""),(9,"fizz"),(10,"buzz"),(11,""),(12,"fizz"),(13,""),(14,""),(15,"fizzbuzz"),(16,""),(17,""),(18,"fizz"),(19,""),(20,"buzz"),(21,"fizz"),(22,""),(23,""),(24,"fizz"),(25,"buzz"),(26,""),(27,"fizz"),(28,""),(29,""),(30,"fizzbuzz")
, etc
It just feels like I'm fighting the syntax more than I should. I've seen other questions for this in Haskell, but I'm looking for the most optimal way to express this in a single statement (trying to understand how to work the syntax better).
The most obvious way to solve FizzBuzz is to loop through a set of integers. In this loop, we use conditional statements to check whether each integer is divisible by three and/or five. The code above takes this approach. First, we store integers one-to–50 in the vector fbnums .
Fizz Buzz is a very simple programming task, asked in software developer job interviews. A typical round of Fizz Buzz can be: Write a program that prints the numbers from 1 to 100 and for multiples of '3' print “Fizz” instead of the number and for the multiples of '5' print “Buzz”.
The rules of the FizzBuzz game are very simple. Say Fizz if the number is divisible by 3. Say Buzz if the number is divisible by 5. Say FizzBuzz if the number is divisible by both 3 and 5. Return the number itself, if the number is not divisible by 3 and 5.
The basic idea is to write a program that prints numbers (1-n), where n is an argument passed in. For multiples of three, you print the word “Fizz”, for multiples of five you print “Buzz. For multiples of both three and five you print “FIzzBuzz”.
We need no stinkin' mod
...
zip [1..100] $ zipWith (++) (cycle ["","","fizz"]) (cycle ["","","","","buzz"])
or slightly shorter
import Data.Function(on)
zip [1..100] $ (zipWith (++) `on` cycle) ["","","fizz"] ["","","","","buzz"]
Or the brute force way:
zip [1..100] $ cycle ["","","fizz","","buzz","fizz","","","fizz","buzz","","fizz","","","fizzbuzz"]
If you insist on a one-liner:
[(x, concat $ ["fizz" | mod x 3 == 0] ++ ["buzz" | mod x 5 == 0]) | x <- [1..100]]
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