Find Related products on Amazon

Shop on Amazon

FizzBuzz Through Monoids

Published on: 2025-06-23 02:46:40

Some decade ago I read a good implementation of fizzbuzz. What set it apart was its excellent modularity. The original article is no longer on the web1 Although I realised just now it is archived., but this is my reconstruction: In[1]: module Main where import Control.Monad (guard) import Data.Foldable (for_) import Data.Maybe (fromMaybe) fizzbuzz i = fromMaybe (show i) . mconcat $ [ "fizz" <$ guard (rem i 3 == 0) , "buzz" <$ guard (rem i 5 == 0) ] main = for_ [1 .. 100] $ putStrLn . fizzbuzz The great thing about this implementation is that if we get the natural change in requirements – that we are supposed to print “zork” for multiples of seven – we can accomodate that change by simply adding the line that does so: In[2]: --- orig.hs 2025-05-23 13:11:29.929652707 +0200 +++ new.hs 2025-05-23 13:18:02.897544701 +0200 @@ -8,6 +8,7 @@ fromMaybe (show i) . mconcat $ [ "fizz" <$ guard (rem i 3 == 0) , "buzz" <$ guard (rem i 5 == 0) + , "zork" <$ guard (rem i 7 == 0) ] main = This wil ... Read full article.