Skip to content

Instantly share code, notes, and snippets.

@m-renaud
Last active December 11, 2017 04:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-renaud/00c12d4f2c9c67b19575a9d380ce0d8f to your computer and use it in GitHub Desktop.
Save m-renaud/00c12d4f2c9c67b19575a9d380ce0d8f to your computer and use it in GitHub Desktop.
Elegant fizzbuzz implementation based on Monoids. Inspired by http://www.parsonsmatt.org/2016/02/27/an_elegant_fizzbuzz.html.
module Main where
import Data.Foldable (fold)
import Data.Maybe (fromMaybe, listToMaybe)
fizzBuzz :: Functor f => f Int -> f String
fizzBuzz =
fmap (fromMaybe <$> show <*> fold rules)
where
rules = [fizz, buzz]
fizz = rule "Fizz" 3
buzz = rule "Buzz" 5
rule str n i = listToMaybe [ str | i `mod` n == 0 ]
main :: IO ()
main =
mapM_ putStrLn (fizzBuzz [1..20])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment