Created
November 16, 2016 16:21
-
-
Save mathiasverraes/763ebf4a7c6ed5e364840e021af5e431 to your computer and use it in GitHub Desktop.
Extensible Monoidal FizzBuzz in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Author
mathiasverraes
commented
Nov 16, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment