Skip to content

Instantly share code, notes, and snippets.

@mathiasverraes
Created November 16, 2016 16:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathiasverraes/763ebf4a7c6ed5e364840e021af5e431 to your computer and use it in GitHub Desktop.
Save mathiasverraes/763ebf4a7c6ed5e364840e021af5e431 to your computer and use it in GitHub Desktop.
Extensible Monoidal FizzBuzz in Haskell
module MonoidalFizzBuzz where
import Data.Monoid
import Data.Maybe
-- based on @mittie https://twitter.com/mittie/status/798257339736453120
monoidalFizzbuzz = zipWith fromMaybe numbers strings
where
fizzes = cycle [Nothing, Nothing, Just "Fizz"]
buzzes = cycle [Nothing, Nothing, Nothing, Nothing, Just "Buzz"]
strings = zipWith (<>) fizzes buzzes
numbers = show <$> [1..]
-- Now a version that allows us to add arbitrary replacement rules
-- without too much hassle.
monoidZip :: (Foldable t, Monoid a) => t [a] -> [a]
monoidZip = foldl1 (zipWith (<>))
extensibleFizzbuzz = zipWith fromMaybe numbers combinedRules
where
becomes n s = cycle $ replicate (n-1) Nothing ++ [Just s]
numbers = show <$> [1..]
combinedRules = monoidZip rules
rules = [
3 `becomes` "Fizz",
5 `becomes` "Buzz",
7 `becomes` "Woo"
]
-- todo: pretty print
@mathiasverraes
Copy link
Author

prettyPrinted = foldl1 (\x y -> x ++ " " ++ y) $ take 105 extensibleFizzbuzz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment