FizzBuzz via the string monoid

haskell monoids

FizzBuzz is a fun little exercise for thinking about conditional statements. The Haskell versions over there were not quite the way I did it, so I figured I’d post a solution here:

f x = if null fizzbuzz then show x else fizzbuzz
   where fizz     = if x `mod` 3 == 0 then "Fizz" else ""
         buzz     = if x `mod` 5 == 0 then "Buzz" else ""
         fizzbuzz = fizz ++ buzz

main = putStr . unlines $ map f [1..100]

The central point is that a separate case for 15 is unnecessary: the effects of this program are expressed in the String monoid so we can almost pretend we are writing as we would in the imperative case. We accumulate the intended effects and then print the output as a side-effect of evaluating “main”.

Yes, I should have used ByteString or Text or whatever, but this is FizzBuzz we are talking about. High-performance and/or parallel FizzBuzz is left as an exercise. 😉