Last active
December 17, 2016 17:24
-
-
Save deque-blog/3e8ebe35f0ec15178a39c9c9b25616b3 to your computer and use it in GitHub Desktop.
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
{-# LANGUAGE OverloadedStrings #-} | |
import Data.Monoid((<>)) | |
import qualified Data.Text.Lazy as T | |
import qualified Data.Text.Lazy.Builder as B | |
-- The API of the fizz buzz | |
type Rule = B.Builder -> Int -> B.Builder | |
fizzBuzz' :: [Rule] -> Int -> B.Builder | |
fizzBuzz' rules i = foldl (\out rule -> out <> rule out i) "" rules | |
-- Helper function to build the rules | |
defaultRule :: Rule | |
defaultRule s n | |
| s == mempty = B.fromLazyText $ T.pack (show n) | |
| otherwise = "" | |
makeRule :: Int -> T.Text -> Rule | |
makeRule d out _ n | |
| mod n d == 0 = B.fromLazyText out | |
| otherwise = "" | |
-- Usage | |
testFizzBuzz :: IO () | |
testFizzBuzz = do | |
let fizzBuzz = fizzBuzz' [makeRule 3 "fizz", makeRule 5 "buzz", defaultRule] | |
print $ map fizzBuzz [3, 5, 7, 15] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment