Last active
May 9, 2020 08:12
-
-
Save lgastako/d4fa392cbe85cbfae7dfa5e18c14a2a4 to your computer and use it in GitHub Desktop.
This file contains 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
{-# LANGUAGE NoImplicitPrelude #-} | |
{-# LANGUAGE OverloadedStrings #-} | |
module Fizz where | |
import Protolude | |
fizzBuzz :: IO () | |
fizzBuzz = run fizzBuzzRules | |
deluxeFizzBuzz :: IO () | |
deluxeFizzBuzz = run deluxeFizzBuzzRules | |
fizzBuzzRules :: CompiledRules | |
fizzBuzzRules = compile | |
[ rule 3 "Fizz" | |
, rule 5 "Buzz" | |
] | |
deluxeFizzBuzzRules :: CompiledRules | |
deluxeFizzBuzzRules = compile | |
[ rule 2 "Klunk" | |
, rule 3 "Fizz" | |
, rule 5 "Buzz" | |
] | |
type Rule = (Int, Text) | |
type CompiledRules = Int -> Maybe Text | |
run :: CompiledRules -> IO () | |
run = runWithRange [1..100] | |
runWithRange :: [Int] -> CompiledRules -> IO () | |
runWithRange range rules = traverse_ (putText . genericFizz rules) range | |
genericFizz :: CompiledRules -> Int -> Text | |
genericFizz rules n = fromMaybe (show n) (rules n) | |
compile :: [Rule] -> CompiledRules | |
compile = foldMap comp | |
where | |
comp (n, s) i | |
| i `mod` n == 0 = Just s | |
| otherwise = Nothing | |
rule :: Int -> Text -> Rule | |
rule = (,) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment