Last active
December 11, 2017 04:21
-
-
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.
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 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