Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Nov 16, 2016

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
You can’t perform that action at this time.